【问题标题】:how to open and read a binary file in C++ by a given bin file?如何通过给定的 bin 文件在 C++ 中打开和读取二进制文件?
【发布时间】:2016-07-15 20:05:46
【问题描述】:

有没有人可以帮我检查我做错了什么?或者解释一下为什么?我是初学者,我尽力打开二进制文件。但它只是用完“文件已打开”“0”。什么都没有出来。

目标: Count3s 程序打开一个包含 32 位整数 (ints) 的二进制文件。您的程序将计算此数字文件中值 3 的出现次数。您的目标是了解如何打开和访问文件并应用您对控制结构的了解。包含程序使用的数据的文件的名称是“threesData.bin”。

我的代码如下,如果你知道,请帮助我。提前谢谢!

#include <iostream>
#include <fstream>
using namespace std;

int main()
{
int count=0 ;
ifstream myfile;
myfile.open( "threesData.bin", ios::in | ios :: binary | ios::ate);

if (myfile)
{
    cout << "file is open " << endl;
    cout << count << endl;    }

else 
    cout << "cannot open it" << endl;


return 0;    
}

【问题讨论】:

  • 您只有打开文件的代码。您没有任何代码行来读取数据。
  • 您可能想阅读例如this openmode reference 表示ate“打开后立即搜索到流的末尾”。

标签: c++ binaryfiles ifstream ofstream


【解决方案1】:

首先你应该从用二进制模式打开的文件中读取

  myfile.read (buffer,length);

buffer 应定义为

  int data;

并用作

  myfile.read (&data,sizeof(int));

第二个重点是从文件中读取多个数字 - 您需要由检查流的条件控制的循环。例如:

  while (myfile.good() && !myfile.eof())
  {
       // read data
       // then check and count value
  }

最后一件事,你应该在读完之后关闭文件,这个文件已经成功打开了:

  myfile.open( "threesData.bin", ios::binary); 
  if (myfile)
  {
       while (myfile.good() && !myfile.eof())
       {
           // read data
           // then check and count value
       }
       myfile.close();
       // output results
   }

还有一些额外的提示:

1) int 并不总是 32 位类型,因此请考虑使用来自 &lt;cstdint&gt;int32_t;如果你的数据超过1个字节,可能字节顺序很重要,但任务描述中没有提到

2) read 允许每次调用读取多个数据对象,但在这种情况下,您应该读取数组而不是一个变量

3) 阅读并尝试来自references 和其他可用资源(如this)的示例。

【讨论】:

猜你喜欢
  • 2016-05-02
  • 1970-01-01
  • 2011-01-26
  • 2016-03-11
  • 2015-07-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多