【问题标题】:c++ reading integers from binary file, missing some datac ++从二进制文件中读取整数,丢失一些数据
【发布时间】:2017-07-17 01:04:12
【问题描述】:

我正在使用以下方法将 100,000 个整数保存到二进制文件中:

    for(unsigned int i = 0; i < 100000; i++){
        temp = generateRand(99999);
        file.write(reinterpret_cast<const char*>(&temp),sizeof(temp));
    }

我正在尝试从这个文件中读取整数,并将它们保存到一个向量中。

ifstream ifile;
ifile.open("test.bin",ios::binary);

ifile.seekg(0, ifile.end);
long size = ifile.tellg();
ifile.seekg(0, ifile.beg);

int restore = 0;
int count = 0;

while(ifile.tellg() < size){
    ifile.read(reinterpret_cast<char*>(&restore), sizeof(restore));
    v.push_back(restore);
    count++;
}

但是,我似乎只能读取 99328 个整数,而不是 100000。我对二进制文件的读/写比较陌生,你们能帮帮我吗?

【问题讨论】:

  • temp 的类型是什么?你得到的文件的大小是多少?你如何定义/打开fileifile
  • 哦,temp 是 int 类型。 generateRand 函数只生成随机整数。
  • 在阅读之前你会关闭或销毁file吗?
  • 没有。我在最后关闭文件和 ifile。
  • 好吧,这就是你的答案)

标签: c++ file io binary


【解决方案1】:

看起来file 对象在读取开始时仍处于打开状态,这会导致所描述的行为。

尝试调用file.close() 刷新缓冲区,然后再初始化ifile

你还会发现一次读取整个向量可以大大加快这个过程。

【讨论】:

    【解决方案2】:

    它对我有用。可能您忘记使用ios::binary 标志或关闭流?

    #include <vector>
    #include <fstream>
    #include <iostream>
    
    using namespace std;
    
    void write() {
      ofstream file;
      file.open("temp.data", ios::binary);
      for(unsigned int i = 0; i < 100000; i++){
        int temp = 0; // I don't know the generateRandom(...) function
        file.write(reinterpret_cast<const char*>(&temp),sizeof(temp));
      }
    }
    
    void read() {
      ifstream ifile;
      ifile.open("temp.data", ios::binary);
    
      ifile.seekg(0, ifile.end);
      long size = ifile.tellg();
      ifile.seekg(0, ifile.beg);
    
      int restore = 0;
      vector<int> v;
      while(ifile.tellg() < size){
        ifile.read(reinterpret_cast<char*>(&restore), sizeof(restore));
        v.push_back(restore);
      }
    
      cout << v.size() << endl;
    }
    
    int main()
    {
      write();
      read();
    
      return 0;
    }
    

    【讨论】:

    • 谢谢。我必须使用 file.close() 来刷新缓冲区!
    • +1 - 更好的程序结构通过在超出范围时自动关闭输出文件来解决问题。
    • 哦,所以如果你使用上面的函数——write() 和 read() 函数,你不必明确地使用 close() 函数?
    • 是的,当ofstreamifstream 对象被销毁时,它也会自动关闭。
    • 非常感谢 cbuchart。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-04-04
    • 2015-11-11
    • 1970-01-01
    • 2021-07-02
    • 1970-01-01
    • 2012-02-27
    相关资源
    最近更新 更多