|
fread 库函数用来从一个文件流中读取数据。
#include <stdio.h>
size_t fread(void *ptr, size_t size, size_t nitems, FILE *stream);
数据从指针 ptr 所指向的流(stream)读取数据到缓冲区。fread 和 fwrite 都处理数据记录。参数 size 为数据记录的大小;参数 nitmes 表示要传送的记录数。函数成功时返回读取数据记录的条数。在文件的末尾,如果所剩数据少于一条记录数中的指定量,那么也会被当作1条来返回,这也包括0。
例如,有一个叫做 new-1 的文件,里面的内容为:The fread library function is used to read data from a file stream. Data is read into a data buffer given
by ptr from the stream, stream.
测试程序代码如下:#include <stdio.h>
#include <sys/types.h>
int main()
{
FILE *new;
size_t item;
char buf[100];
new = fopen("new-1", "r");
item = fread(buf, 10, 4, new);
printf("fread returned item count are: %d\n", item);
return 0;
}
编译后运行程序,则有:[root@localhost Desktop]# ./fopen_read.exe
fread returned item count are: 4 说明:程序中,一次读取10个字节数据记录,一共读 4 次。因为 new-1 文件中的内容大于 40 个字节,那么自然就返回 4 。
修改 new-1 中内容为(共38个字符):The fread library function is used to
所以再次运行程序时,返回值为 3 ,尽管在程序中指定的是要读出 4 条记录。
修改 new-1 中内容为(只有 3 个字符):
所以再次运行程序时,看到返回值为 0 。这是因为,文件中的内容连一次性要求读取10个字节这个要求都无法满足。 |
|