C++官网参考链接:https://cplusplus.com/reference/cstdio/fread/
函数
<cstdio>
fread
size_t fread ( void * ptr, size_t size, size_t count, FILE * stream );
从流中读取数据块
从stream中读取count个元素的数组,每个元素的大小为size字节,并将它们存储在ptr指定的内存块中。
流的位置指示符按读取的字节总数向前移动。
如果成功,则读取的字节总数为(size*count)。
形参
ptr
指向内存块的指针,其大小至少为(size*count)个字节,转换为void*。
size
要读取的每个元素的大小(以字节为单位)。
size_t是无符号整型。
count
元素数量,每个元素的大小为size字节。
size_t是无符号整型。
stream
指向指定输入流的FILE对象的指针。
返回值
返回成功读取的元素总数。
如果该数字与count形参不同,则要么发生了读取错误,要么在读取时已到达文件结束。在这两种情况下,都设置了适当的指示符,可以分别用ferror和feof进行检查。
如果size或count为0,则函数返回0,并且流状态和ptr所指向的内容保持不变。
size_t是无符号整型。
用例
/* fread example: read an entire file */
#include <stdio.h>
#include <stdlib.h>
int main () {
FILE * pFile;
long lSize;
char * buffer;
size_t result;
pFile = fopen ( "myfile.bin" , "rb" );
if (pFile==NULL) {fputs ("File error",stderr); exit (1);}
// obtain file size:
fseek (pFile , 0 , SEEK_END);
lSize = ftell (pFile);
rewind (pFile);
// allocate memory to contain the whole file:
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;
}
这段代码将myfile.bin加载到动态分配的内存缓冲区中,该缓冲区可用于将文件的内容作为数组操作。
另请参考
fwrite Write block of data to stream (function)
fgetc Get character from stream (function)
fscanf Read formatted data from stream (function)