如何读取二进制文件并在屏幕上打印3?

时间:2017-02-24 22:02:25

标签: c++ binary

我想读取整数类型的二进制文件,并在文件中打印出3个数字的出现次数。我以某种方式编写了一个打开并读取二进制文件的程序。

以下是我面临的几个问题:

  1. 如果我尝试在终端上打印文件,则继续执行 永远,循环永远不会结束。
  2. 我不知道如何从中过滤掉3。
  3. 这是我的代码:

    #include <iostream>
    #include <fstream>
    using namespace std;
    
    int main () {
    streampos size;
    char * memblock;
    
    ifstream file ("threesData.bin", ios::in|ios::binary|ios::ate);
    if (file.is_open())
    {
        size = file.tellg();
        memblock = new char [size];
        file.seekg (0, ios::beg);
        file.read (memblock, size);
        file.close();
    
        cout << "the entire file content is in memory";
    
        for (int i = 0; i < size; i += sizeof(int))
        {
            cout << *(int*)&memblock[i] << endl;
        }
    
    
        delete[] memblock;
    }
    else 
        cout << "Unable to open file";
    
    return 0;
    }
    

1 个答案:

答案 0 :(得分:1)

以下是实现您的要求的方法:

int main()
{
  unsigned int quantity = 0U;
  ifstream file ("threesData.bin", ios::in|ios::binary|ios::ate);
  uint8_t byte;
  while (file >> byte)
  {
    if (byte == 3U)
    {
      ++ quantity;
    }
  }
  cout << "The quantity of 3s is: " << quantity << endl;
  return 0;
}

第一步应始终首先使用简单版本。仅在必要时进行优化。

为文件分配内存并读取整个文件是一种优化。例如,您的平台可能没有足够的可用内存来在处理之前将整个文件读入内存。