fread and fwrite parameters in C

≡放荡痞女 提交于 2019-12-11 05:07:21

问题


I am trying to adapt a matlab program to C, my problem is in the fwrite and fread function. On matlab I have:

fid = fopen ('sweep_100_3400.pcm','rb');
s = fread (fid, 'int16');

My doubt is, in C there are two more parameters in fread and fwrite function.

fread(void*, size_t, size_t, FILE*);
fwrite(const void*, size_t, size_t, FILE*);

In my C code I have:

arq = fopen("C:\\Users\\iago_\\Desktop\\MediaMovel\\sweep_100_3400.pcm", "rb");
fread(x, sizeof(double), itera, arq);
fclose(arq);

x is the vector where the data of my file will be saved.
sizeof(double) is the length of the data (I've declared all double)
arq is the pointer to the file.

The third parameter is a size_t, to adapt my matlab program, in this parameter should I use the media length or the vector size?

(I am encoding a moving average, the media length is informed by the user and the vector size is the length of my input file).

For the fwrite function I have the same doubt about the parameters.

arq=fopen("C:\\Users\\iago_\\Desktop\\MediaMovel\\saida_medial_movel_c.pcm", "wb");
fwrite(saida, sizeof(double), itera, arq);
fclose(arq); 

回答1:


fread() parameters are

size_t fread(void *ptr, size_t size, size_t nmemb, FILE *stream);

where nmemb is multiple of size function of read. So second parameter should be sizeof your vector and third should number of vectors you want to read from file pointer. Also there is but of confusion about matlab fread call. second param in matlab fread call is int16 which is 2 bytes, but in c fread call you have passed second param as sizeof(double) which is 8 bytes.



来源:https://stackoverflow.com/questions/39086285/fread-and-fwrite-parameters-in-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!