我一直很难写入二进制文件并回读。我基本上是在写这种格式的记录
1234|ABCD|efgh|IJKL|ABC
在编写此记录之前,我会写出整个记录的长度(using string.size())
,然后使用ofstream
将记录写入二进制文件,如下所示:
int size;
ofstream studentfile;
studentfile.open( filename.c_str(),ios::out|ios::binary );
studentfile.write((char*)&size,sizeof(int));
studentfile.write(data.c_str(),(data.size()*(sizeof(char))));
cout << "Added " << data << " to " << filename << endl;
studentfile.close();
我在其他地方阅读了这些数据
ifstream ifile11;
int x;
std::string y;
ifile11.open("student.db", ios::in |ios::binary);
ifile11.read((char*)&x,sizeof(int));
ifile11.read((char*)&y,x);
cout << "X " << x << " Y " << y << endl;
首先我将记录的长度读入变量x,然后将记录读入字符串y。问题是,输出显示x为'0','y'为空。
我无法解决这个问题。非常感谢能够研究这个问题并提供一些见解的人。
谢谢
答案 0 :(得分:2)
您不能以这种方式读取字符串,因为std::string
实际上只是指针和大小成员。 (尝试做std::string s; sizeof(s)
,无论你将字符串设置为什么,大小都是常量。)
而是将其读入临时缓冲区,然后将该缓冲区转换为字符串:
int length;
ifile11.read(reinterpret_cast<char*>(&length), sizeof(length));
char* temp_buffer = new char[length];
ifile11.read(temp_buffer, length);
std::string str(temp_buffer, length);
delete [] temp_buffer;
答案 1 :(得分:0)
我知道我正在回答我自己的问题,但我严格认为这些信息对每个人都有帮助。在大多数情况下,约阿希姆的答案是正确和有效的。但是,我的问题背后有两个主要问题:
1. The Dev-C++ compiler was having a hard time reading binary files.
2. Not passing strings properly while writing to the binary file, and also reading from the file. For the reading part, Joachim's answer fixed it all.
Dev-C ++ IDE没有帮助我。它错误地从二进制文件中读取数据,而且即使使用temp_buffer也没有我这样做。 Visual C ++ 2010 Express已正确识别此错误,并抛出运行时异常并使我免于被误导。 一旦我将所有代码都放入一个新的VC ++项目中,它就会恰当地向我提供错误消息,以便我可以解决所有问题。
所以,请不要使用Dev-C ++,除非你想遇到像thiis这样的真正麻烦。此外,在尝试阅读字符串时,Joachim的答案将是理想的方式。