0
回答
请问fread(c)读取wave文件(二进制)中间 莫名中断的原因!
华为云实践训练营,热门技术免费实践!>>>   

struct wav_struct{

....

unsigned long subchunk2size; //wave数据长度(字节)
short *data;(数据是两个字节  一个采样点)

}

int main {

...

fp = fopen("C:/Users/Administrator/Desktop/011c020a.wav", "rb");//open a wave file (8k_16bits)

fp2 = fopen("C:/Users/Administrator/Desktop/aa.txt", "w");

fseek(fp, 40L, SEEK_SET);
fread(&wave.subchunk2size, sizeof(wave.subchunk2size), 1, fp);//wave文件头中第41-44L是wave数据的长度
wave.data = (short*)malloc(sizeof(short)*wave.subchunk2size/2);  //开辟空间

fseek(fp, 44L, SEEK_SET);  //从第45个字节开始读取数据
i = 0;
while (!feof(fp)){
fread(&wave.data[i], sizeof(short), 1, fp);    
//fprintf(fp2, "%d\n", wave.data[i]);
i++;

printf("%x\n",c);
c = fgetc(fp);
//printf("%x\n", c);     

}

问题:  无论是打印到aa.txt(fp2),还是输出到DOS win中,均出现一种诡异情况:前面输出很正常,但读到文件中间,fp出现异常,中断了,

如上图,读到第2208个采样点(short)还是正确的(用matlab验证过),但之后似乎碰到feof(fp),抱歉,表达不清。

我已经用多个wavefile验证,均出现此类情况。

求大神帮助!

#include <stdio.h>
#include <stdint.h>
#include <iomanip>

struct wav_struct{
	unsigned long chunksize;
	unsigned long subchunksize;
	unsigned short numchannels;
	unsigned long samplerate;
	unsigned long byterate;
	unsigned short blockalign;
	unsigned short  bitspersample;
	unsigned long subchunk2size;
	short *data;
	//int16_t *data;
	//unsigned char *data;
};


int main(){
	int i, j;
	wav_struct wave;
	FILE *fp, *fp2;

	fp = fopen("C:/Users/Administrator/Desktop/011c020a.wav", "rb");
	if (fp == NULL){
		printf("can not open file");
		exit(1);
	}
	fp2 = fopen("C:/Users/Administrator/Desktop/aa.txt", "w");
	if (fp == NULL){
		printf("can not open file");
		exit(1);
	}
	
	fseek(fp, 40L, SEEK_SET);
	fread(&wave.subchunk2size, sizeof(wave.subchunk2size), 1, fp);

	
	wave.data = (short*)malloc(sizeof(short)*wave.subchunk2size/2);	

	int c=0 ;	
	fseek(fp, 44L, SEEK_SET);
	i = 0;
	while (!feof(fp)){
		fread(&wave.data[i], sizeof(short), 1, fp);
		//fprintf(fp2, "%d\n", wave.data[i]);
		i++;
		
		printf("%x\n",c);
		c = fgetc(fp);
		//printf("%x\n", c);
		
	}	

	fclose(fp2);
	fclose(fp);
}




<无标签>
举报
小青蛇
发帖于3年前 0回/216阅
顶部