21xrx.com
2025-07-14 09:26:48 Monday
文章检索 我的文章 写文章
C++中的 fread 函数
2023-06-28 18:26:43 深夜i     39     0
C++ fread 文件操作 二进制 缓冲区

在C++语言中,文件(file)处理是非常重要的一部分,因为很多时间我们需要从文件中读取或向文件中写入数据。C++中提供了一系列与文件处理相关的头文件,如 ,其中 头文件中的fread函数是一个非常常用和重要的函数。

fread函数的作用是从指定的流中读取二进制数据块,包括文件等。它的声明如下:

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

参数说明:

- ptr:指向存储数据的指针。

- size:每个数据块的字节数。

- count:指定要读取的块数。

- stream:指向要读取的流(文件)。

函数返回值:

如果成功读取,则该函数返回读取的数据块数,否则返回0。

下面是一个使用fread函数读取文件内容的例子:

#include <cstdio>
#include <iostream>
using namespace std;
int main () {
 FILE * pFile;
 size_t result;
 pFile = fopen ("example.bin" , "rb");
 if (pFile==NULL) {fputs ("File error",stderr); exit (1);}
 // obtain file size:
 fseek (pFile , 0 , SEEK_END);
 int lSize = ftell (pFile);
 rewind (pFile);
 // allocate memory to contain the whole file:
 char * buffer = (char*) malloc (sizeof(char)*lSize);
 if (buffer == NULL) {fputs ("Memory error",stderr); exit (2);}
 // copy the file into the buffer:
 result = fread (buffer,1,lSize,pFile);
 if (result != lSize) {fputs ("Reading error",stderr); exit (3);}
 // the whole file is now loaded in the memory buffer.
 // terminate
 fclose (pFile);
 free (buffer);
 return 0;
}

该例子中,我们首先打开一个二进制文件 example.bin,并获取文件大小,接着为文件创建一个指定大小的内存块,最后在内存块中读入文件中所有内容。

总的来说,fread函数是一个非常方便、灵活的读取文件内容的工具,在文件处理中使用频率非常高。我们可以使用fread函数来读取各种文件格式,需要读取的数据块长度和读取块数也可以按照需求自由设置。

  
  

评论区