1 函数原型
fread():从指定流stream中读取数据块,函数原型如下:
size_t fread ( void * ptr, size_t size, size_t count, FILE * stream );
cstdio库描述如下:
Read block of data from stream
1. Reads an array of count elements, each one with a size of size bytes, from the stream and stores them in the block of memory specified by ptr.
2. The position indicator of the stream is advanced by the total amount of bytes read.
3. The total amount of bytes read if successful is (size*count).
2 参数
fread()函数有四个参数ptr、size、count和stream:
- 参数ptr是指向某内存区域的指针,类型为void*型;ptr指向的内存区域用于存储从文件中读取的数据块;
- 参数size是fread()函数要读取的数据项的大小,类型为size_t型,单位是字节;
- 参数count是fread()函数要读取的数据项的个数,类型为size_t型;
- 参数stream是fread()函数要读取的流,类型为FILE*;stream主要是文件流,就是fopen()函数的返回值。
cstdio库描述如下:
ptr
1. Pointer to a block of memory with a size of at least (size*count) bytes, converted to a void*.
size
1. Size, in bytes, of each element to be read.
2. size_t is an unsigned integral type.
count
1. Number of elements, each one with a size of size bytes.
2. size_t is an unsigned integral type.
stream
1. Pointer to a FILE object that specifies an input stream.
3 返回值
fread()函数的返回值类型为size_t型,返回从文件成功读取的数据项的数量。
cstdio库描述如下:
1. The total number of elements successfully read is returned.
2. If this number differs from the count parameter, either a reading error occurred or the end-of-file was reached while reading.
3. In both cases, the proper indicator is set, which can be checked with ferror and feof, respectively.
4. If either size or count is zero, the function returns zero and both the stream state and the content pointed by ptr remain unchanged.
5. size_t is an unsigned integral type.
fread()函数,预期读取m项,成功读取n项:
| 读取比较 | 读取状况 | 读取结果 | 返回值 | 状态设置 |
|---|---|---|---|---|
| n=m | 全部成功读取 | 读取成功 | 返回n | NA |
| 0≤n<m | 遇到读取错误 | 读取成功 | 返回n | 设置错误指示符(ferror) |
| 0≤n<m | 遇到文件末尾 | 读取成功 | 返回n | 设置文件结束指示符(feof) |
4 示例
使用fread()函数读空文件,示例代码如下所示:
int main()
{
//
FILE* fp = NULL;
int rdata = 0;
//
fp = fopen("1.dat", "rb");
if (fp == NULL) {
perror("Failed to open file ");
exit(1);
}
//
while(fread(&rdata, sizeof(int), 1, fp) > 0) {
printf("%#x\n", rdata);
}
//
fclose(fp);
//
return 0;
}
文件内容如下图所示:

代码运行结果如下图所示:

本文详细介绍了fread()函数的使用方法,包括其函数原型、参数说明、返回值解释及示例代码。通过阅读本文,读者可以了解到如何利用fread()从文件中读取固定大小的数据块。
2229

被折叠的 条评论
为什么被折叠?



