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

时间:2018-09-25 00:45:00

标签: c++

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

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

这很好,但是我的老师说我不应该逐行读取文件,因为这会增加I / O量。因此,现在我需要一次读取整个二进制文件。我怎样才能做到这一点?有人可以帮忙吗?

2 个答案:

答案 0 :(得分:1)

首先请注意,如果将文件读取到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;
}

答案 1 :(得分:0)

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);
}