没有从bin文件获取字符串

时间:2016-06-21 17:15:57

标签: c++ string fstream

#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);仍然做同样的事情

1 个答案:

答案 0 :(得分:0)

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

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

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

后来:

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

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