如何在C++中打开并读取给定的二进制文件?

3

有没有人能帮我检查一下哪里出了错?或者解释一下为什么?我是初学者,尽力打开二进制文件。但它只显示"file is open"和"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;    
}

3
你只有代码来打开文件,没有任何读取数据的代码行。 - undefined
你可能想阅读一下这个openmode参考链接,它解释了ate的含义是“在打开后立即定位到流的末尾”。 - undefined
1个回答

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位类型,因此考虑使用<cstdint>中的 int32_t;如果您的数据超过1个字节,则字节顺序可能很重要,但在任务描述中没有提到。

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

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


或者更好的是,使用unsigned char buffer[bufsiz];并根据需要解码字节。 - undefined
一如既往,解决这个并不太难的问题有无数种方法。Nydia应该从简单的开始,然后逐渐转向高级的C++编程。 - undefined
为什么在循环条件中使用iostream::eof被认为是错误的?你应该使用while(myfile.read(&data,sizeof(int))){ /* 读取成功 */} - undefined
手动关闭流也不是标准的做法 我需要手动关闭ifstream吗? - undefined

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接