gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 05:25:12 25 4
gpt4 key购买 nike

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

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com