【问题标题】:Not getting string from bin file没有从 bin 文件中获取字符串
【发布时间】:2016-06-21 17:15:56
【问题描述】:
#include <iostream>
#include <cmath>
#include <fstream>
#include <cstring>
#include <string>
using namespace std;
int main()
{
int numcount; //amount of numbers
int numb; //temporary number for writing reaction
fstream fbin ("filename.bin", ios::binary | ios::out);
if (!fbin){
    cout << "err";
    return -1;

}
char thing[6]; //reading of Done!
cout << "Starting Write Sequence...\n";
cout << "How many numbers do you want to write?\n";
cin >> numcount;
cout << "Okay, " << numcount << " numbers.\n";
fbin.write((char*)(&numcount), 4); //writes amount of numbers to first
for(int i = 0; i < numcount; i++){ //loop that writes numcount numbers to file
    cout << "Enter number " << i + 1 << ": ";
    cin >> numb;
    cout << "Number " << numb << " entered. Writing...\n";
    fbin.write((char*)(&numb), 4);
}
fbin.write("Done!", sizeof("Done!") - 1);
fbin.seekp(numcount * 4 + 4); //Finds position of Done!. numcount * 4 because normal integers are 4 bytes,
//and + 4 because I also need to include numcount in the file, so it can be read.
fbin.read(thing, 5);
cout << thing << "\n";
cout << "\"Done!\" should have appeared before this!";
}

这段代码的最后一部分应该打印出来

Done!

到控制台,而是打印@。

这是二进制文件中包含 4 个数字(7、5、8、7)的内容:

04 00 00 00 07 00 00 00 05 00 00 00 08 00 00 00 07 00 00 00 44 6F 6E 65 21

....................Done!

编辑:意外删除 fbin.read(thing, 5);仍然做同样的事情

【问题讨论】:

  • 你从哪里读过代码中的thing缓冲区??
  • 看起来像是错字。 fbin.seekp 应该是 fbin.seekg 因为你想推进 get 指针而不是 put 指针
  • @NathanOliver 仍然做同样的事情(@ 符号)
  • @LightnessRacesinOrbit 我该如何解决这个问题?
  • @LightnessRacesinOrbit 我正在尝试将 Done! 从 filename.bin 读取到控制台,作为字符串 thing

标签: c++ string fstream


【解决方案1】:

您正在以“输出”模式打开流,并且您正在寻找 seekp 而不是 seekg。这会破坏您从文件中读取以及在正确位置进行读取的能力。对您的操作结果执行一些错误检查会发现这一点!

由于你想使用二进制模式,你不能完全省略流标志,所以我建议:

fstream fbin("filename.bin", ios::binary | ios::in | ios::out);
//                                      ^^^^^^^^^^

然后:

fbin.seekg(numcount * 4 + 4);
//       ^

此外,您不应该假设整数是四个字节宽。所有这些神奇的数字4s 都应该替换为sizeof(int)

【讨论】:

  • 谢谢,我需要 ios::in
猜你喜欢
  • 2015-08-06
  • 1970-01-01
  • 1970-01-01
  • 2013-06-24
  • 2012-09-20
  • 1970-01-01
  • 2013-04-10
  • 2018-08-22
相关资源
最近更新 更多