c ++使用fstream从二进制文件读取字符串

use*_*225 2 c++ fstream

我正在尝试从二进制文件中读取字符串,但似乎无法使其正常工作。我是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;
}
Run Code Online (Sandbox Code Playgroud)

R S*_*ahu 5

这是有问题的路线。

    iFile.read((char *)&Name, StringLength);
Run Code Online (Sandbox Code Playgroud)

您正在将char*a 的一部分std::string直接读入的记忆Name

您需要保存字符串的大小以及字符串的大小,以便在读取数据时会知道读取数据需要多少内存。

代替

oFile.write(Name.c_str(), StringLength);
Run Code Online (Sandbox Code Playgroud)

您将需要:

size_t len = Name.size();
oFile.write(&len, sizeof(size_t));
oFile.write(Name.c_str(), len);
Run Code Online (Sandbox Code Playgroud)

在返回的途中,您将需要:

iFile.read(&len, sizeof(size_t));
char* temp = new char[len+1];
iFile.read(temp, len);
temp[len] = '\0';
Name = temp;
delete [] temp;
Run Code Online (Sandbox Code Playgroud)