我正在尝试从二进制文件中读取字符串,但似乎无法让它工作。我是 c++ 的新手。有人可以帮忙吗?谢谢。
string Name = "Shaun";
unsigned short int StringLength = 0;
int main()
{
StringLength = Name.size();
ofstream oFile("File.txt", ios::binary|ios::out);
oFile.write((char*)&StringLength, sizeof(unsigned short int));
oFile.write(Name.c_str(), StringLength);
oFile.close();
StringLength = 0;
Name = "NoName";
ifstream iFile("File.txt", ios::binary|ios::in);
if(!iFile.is_open())
cout << "Failed" << endl;
else
{
iFile.read((char *)&StringLength, sizeof(unsigned short int));
iFile.read((char *)&Name, StringLength);
}
cout << StringLength << " " << Name << endl;
system("Pause>NUL");
return 0;
}
最佳答案
这是有问题的行。
iFile.read((char *)&Name, StringLength);
您正在将 std::string
的 char*
部分直接读取到 Name
的内存中。
你需要保存字符串的大小以及字符串,这样当你读取数据时,你就知道读取数据需要多少内存。
而不是
oFile.write(Name.c_str(), StringLength);
您需要:
size_t len = Name.size();
oFile.write(&len, sizeof(size_t));
oFile.write(Name.c_str(), len);
在回来的路上,您需要:
iFile.read(&len, sizeof(size_t));
char* temp = new char[len+1];
iFile.read(temp, len);
temp[len] = '\0';
Name = temp;
delete [] temp;
关于C++ 使用fstream从二进制文件中读取字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61913148/