跳到主要内容

C++ fread() 函数

fread() 函数原型

size_t fread(void * buffer, size_t size, size_t count, FILE * stream);

fread() 函数从给定的输入流中读取 count 个对象,每个对象大小为 size 字节。它类似于调用 fgetc() size 次来读取每个对象。根据读取的字符数量,文件位置指示器会递增。

如果在读取文件时发生任何错误,流的文件位置指示器的结果值是不确定的。

如果对象不是平凡可复制的,行为是未定义的。

如果 sizecount 为零,则对 fread 的调用将返回零,不执行其他操作。

它定义在 <cstdio> 头文件中。

fread() 参数

  • buffer: 指向用于存储对象的内存块的指针。
  • size: 每个对象的大小(以字节为单位)。
  • count: 要读取的对象数量。
  • stream: 用于读取数据的文件流。

fread() 返回值

fread() 函数返回成功读取的对象数量。如果发生错误或文件结束条件,返回值可能小于 count

示例 1:fread() 函数如何工作

#include <iostream>
#include <cstdio>

using namespace std;

int main()
{
FILE *fp;
char buffer[100];

fp = fopen("data.txt","rb");
while(!feof(fp))
{
fread(buffer,sizeof(buffer),1,fp);
cout << buffer;
}

return 0;
}

假设文件包含以下数据:

Dennis Ritchie : C
Bjarne Stroustrup : C++
Guido van Rossum : Python
James Gosling : Java

当你运行程序时,输出将会是:

Dennis Ritchie : C
Bjarne Stroustrup : C++
Guido van Rossum : Python
James Gosling : Java

示例 2:当 count 或 size 为零时 fread() 函数如何工作

#include <iostream>
#include <cstdio>

using namespace std;

int main()
{
FILE *fp;
char buffer[100];
int retVal;

fp = fopen("data.txt","rb");

/* 当 count 为零时 */
retVal = fread(buffer,sizeof(buffer),0,fp);
cout << "当 count = 0 时,返回值 = " << retVal << endl;

/* 当 size 为零时 */
retVal = fread(buffer,0,1,fp);
cout << "当 size = 0 时,返回值 = " << retVal << endl;

return 0;
}

当你运行程序时,输出将会是:

当 count = 0 时,返回值 = 0
当 size = 0 时,返回值 = 0