我正在尝试从二进制文件中读取字符串,但似乎无法使其正常工作。我是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);
您正在直接将char*
a的部分读std::string
入的记忆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;
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句