c++ - 如何通过给定的 bin 文件打开和读取 C++ 中的二进制文件?

标签 c++ binaryfiles ifstream ofstream

有没有人可以帮我检查我哪里做错了?或者解释为什么?我是初学者,我尽力打开二进制文件。但它只是用完“文件已打开”“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;    
}

最佳答案

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

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

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

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

关于c++ - 如何通过给定的 bin 文件打开和读取 C++ 中的二进制文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38404308/

相关文章:

c++ - 如何加快逐行读取 ASCII 文件的速度? (C++)

C++,fstream,从文件中读取没有给出正确的结果

c# - 未调用 WH_KEYBOARD_LL Hook

c++ - GNU makefile 规则和依赖项

r - 在 R 中写入二进制文件

c++ - 使用 fstream 读取二进制文件并将结果存储在 vector 中

c++ - 纹理中的 OpenGL 片段着色器

python - SWIG:将 std::map 访问器与 shared_ptr 一起使用?

C:读取二进制问题

c++ - 为什么我的 ifstream 程序以错误的顺序读取单词?