【问题标题】:I'm able to read bin file in windows(Visual C++) but not on linux (GCC) [closed]我能够在 Windows(Visual C++)中读取 bin 文件,但不能在 linux(GCC)上读取 [关闭]
【发布时间】:2018-06-20 14:01:45
【问题描述】:

下面是我使用 Visual C++ 的部分代码。 bin文件中的数据看起来像 ff a0 b0 c0 a0 b0 c0 d0

#include<fstream>
#include<vector>
main()
{
    std::ifstream file;
    file.open("file.bin", std::ios::binary);
    vector<uint32_t> data;
    uint32_t temp;
    // now read the data in uint32_t format
    while(file.read(reinterpret_cast<char *>(&temp), sizeof(temp)))
    {
        data.push_back(temp);
    }
    file.close();
}

【问题讨论】:

  • 究竟是什么问题?
  • 调用file.open()等函数时应该检查错误
  • 我的水晶球告诉我这是一个工作目录问题...
  • "bin 文件中的数据看起来像 ff a0 b0 c0 a0 b0 c0 d0" - 在什么地方?在文本编辑器中?当您将二进制值转储为十六进制表示法时?您如何查看这些数据?
  • 您没有检查错误,这就是为什么您没有找到任何错误。当您执行file.open() 时,可能会失败。您应该检查该故障。

标签: c++ visual-studio gcc


【解决方案1】:

您的代码可能会失败,因为文件file.bin 不存在于取决于您的开发平台的工作目录中。

试试这个(这段代码的编译方式与问题中的代码不同):

#include <fstream>
#include <iostream>
#include <vector>

int main()
{
  std::ifstream file;
  file.open("file.bin", std::ios::binary);

  if (file.fail())  // check if file could actually be opened
  {
    // you end up here if the file does not exist
    std::cout << "File could not be opened. Check if it exists.";
    return 1;
  }

  std::vector<uint32_t> data;
  uint32_t temp;
  // now read the data in uint32_t format
  while (file.read(reinterpret_cast<char *>(&temp), sizeof(temp)))
  {
    data.push_back(temp);
  }

  file.close();

  for (auto value : data)
    std::cout << value << "\n";      
}

【讨论】: