C++ fread()

fread() 原型

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

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

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

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

如果 size 或 count 为零,则调用 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");
    
    /*  when count is zero */
    retVal = fread(buffer,sizeof(buffer),0,fp);
    cout << "When count = 0, return value = " << retVal << endl;
    
    /*  when size is zero */
    retVal = fread(buffer,0,1,fp);
    cout << "When size = 0, return value = " << retVal << endl;
    
    return 0;
}

运行程序后,输出将是

When count = 0, return value = 0
When size = 0, return value = 0

另请阅读

你觉得这篇文章有帮助吗?

我们的高级学习平台,凭借十多年的经验和数千条反馈创建。

以前所未有的方式学习和提高您的编程技能。

试用 Programiz PRO
  • 交互式课程
  • 证书
  • AI 帮助
  • 2000+ 挑战