毕业论文开发语言企业开发JAVA技术.NET技术WEB开发Linux/Unix数据库技术Windows平台移动平台嵌入式论文范文英语论文
您现在的位置: 毕业论文 >> linux >> 正文

read()函数为什么设置成count个size这样的大小呢

更新时间:2014-10-21:  来源:毕业论文

函数原型: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的情况。
我有这样用过:
又一次我一个程序比较简单,但是需要保存一些数据,保存成文档的话不安全,我就保存成二进制文件,在每次读写的的时候我就按一个自定义的结构体去读写,别人不知道你结构体是怎么定义的,就没法看出你文件里写什么,(他不知道数据的边界)

就像是网络通讯中的报式套接字和流式套接字,通过分块帮助你在连续的数据里面找到边界,我这样理解的

设为首页 | 联系站长 | 友情链接 | 网站地图 |

copyright©youerw.com 优尔论文网 严禁转载
如果本毕业论文网损害了您的利益或者侵犯了您的权利,请及时联系,我们一定会及时改正。