【问题标题】:how to read a whole binary file at a time with C++如何使用 C++ 一次读取整个二进制文件
【发布时间】:2018-09-25 00:45:00
【问题描述】:

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

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

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

【问题讨论】:

标签: c++


【解决方案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;
}

【讨论】:

【解决方案2】:
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);
}

【讨论】:

  • @user4581301 我刚刚编辑了解决方案。你能投票吗?谢谢
  • 删除了反对票。 Upvote 需要解释,坚持 C++ 习惯而不是 C,而且,由于这个问题已经被回答了数百次,所以需要一些新奇的东西。
猜你喜欢
  • 1970-01-01
  • 2021-04-16
  • 2020-11-20
  • 1970-01-01
  • 2011-02-03
  • 2011-08-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多