如何使用C++一次读取整个二进制文件

how to read a whole binary file at a time with C++

本文关键字:读取 一次 二进制文件 何使用 C++      更新时间:2023-10-16

我在文件中有一些二进制数据。为了读取所有数据,我这样做了:

// open the file
// ...
// now read the file
char data;
while (fread(&data, sizeof(char), 1, input) == 1) {
// do something
}

嗯,这工作得很好,但我的老师说我不应该逐行读取文件,因为这会增加 I/O 的数量。所以现在我需要一次读取整个二进制文件。我该怎么做?谁能帮忙?

unsigned long ReadFile(FILE *fp, unsigned char *Buffer, unsigned long BufferSize)
{
return(fread(Buffer, 1, BufferSize, fp));
}
unsigned long CalculateFileSize(FILE *fp)
{
unsigned long size;
fseek (fp,0,SEEK_END);
size= ftell (fp); 
fseek (fp,0,SEEK_SET);
if (size!=-1)
{
return size;
}
else
return 0;
}

此函数读取文件并将其存储到缓冲区中,因此访问缓冲区可减少 IO 时间:

int main()
{
FILE *fp = fopen("Path", "rb+");// i assume reading in binary mode
unsigned long BufferSize = CalculateFileSize(fp);//Calculate total size of file
unsigned char* Buffer = new unsigned char[BufferSize];// create the buffer of that size
unsigned long  RetValue = ReadFile(fp, Buffer, BufferSize);
}

首先请注意,如果将文件读取到 1 字节缓冲区(代码中的数据变量(,则程序可能会崩溃(如果文件大小> 1(。因此,您需要分配一个缓冲区来读取文件。

FILE *f = fopen(filepath, "rb+");
if (f)
{
fseek(f, 0L, SEEK_END);
long filesize = ftell(f); // get file size
fseek(f, 0L ,SEEK_SET); //go back to the beginning
char* buffer = new char[filesize]; // allocate the read buf
fread(buffer, 1, filesize, f);
fclose(f);
// Do what you want with file data
delete[] buffer;
}