函数原型:size_t fread ( void *buffer, size_t size, size_t count, FILE *stream) ;
为什么设置成count个size这样的大小呢?
感觉size_t fread ( void *buffer, size_t size, FILE *stream) ;这样也行啊!buffer读满返回1,否则返回0.
例如:
char buf[40];
while(1)
{
bzero(buf, 40);
ts=ftell(fp);
ret = fread(buf,10,4,fp);
if(ret == -1)
{
perror("fread:");
exit(1);
}
if(ret < 4)
{
te = ftell(fp);
fwrite(buf,te-ts,1,fp2);
break;
}
if(ret == 4)
fwrite(buf,10,4,fp2);
}
如果 fread(buf,10,4,fp);设置为 fread(buf,40,1,fp);的话(下面做相应修改),程序一样可以运行。那么为什么这样分块读取?有什么好处?
This is a typical std c function declaration. The key is the type of buffer. It is a void*. In c, it means you can send whatever pointer to this buffer. However, c does not have any run time type info, so the function of fread can not tell the count of the array and the size of the element in the array. That is why it requires them as arguments.
As u indicated, it works if u set size to 1, however you should probably expect there are more readings occur since it only read 1 byte from the file each time...
Also, as I addressed, the definition of fread has to follow the convention of c std spec...
One more thing, the return vaule from fread tells u the number of elements that have been filled in the buffer. If u treats buffer as char array for anything, u will not be able to tell the exact number directly...
如果要读取的数据并没有分块的概念,比如是一串文本,那么确实没什么区别。
如果要读取的数据从逻辑上来说是一块一块的,那就有区别了。
比如说,文件里保存了一些结构体的数据,但是不知道有多少。现在要把他们读入到一个结构体数组,用这样的分块读法就可以很方便的知道读入了多少结构体,特别是文件中的数据少于size*count的情况。
我有这样用过:
又一次我一个程序比较简单,但是需要保存一些数据,保存成文档的话不安全,我就保存成二进制文件,在每次读写的的时候我就按一个自定义的结构体去读写,别人不知道你结构体是怎么定义的,就没法看出你文件里写什么,(他不知道数据的边界)
就像是网络通讯中的报式套接字和流式套接字,通过分块帮助你在连续的数据里面找到边界,我这样理解的