Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
439 views
in Technique[技术] by (71.8m points)

c++ Reading string from binary file using fstream

I am trying to read a string from a binary file but cant seem to get it to work. I am a pretty new to c++. Can anybody help please? Thanks.

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;
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

This is the problematic line.

    iFile.read((char *)&Name, StringLength);

You are reading the char* part of a std::string directly into the memory of Name.

You need to save both the size of the string as well as the string so that when you read the data, you would know how much memory you need to read the data.

Instead of

oFile.write(Name.c_str(), StringLength);

You would need:

size_t len = Name.size();
oFile.write(&len, sizeof(size_t));
oFile.write(Name.c_str(), len);

On the way back, you would need:

iFile.read(&len, sizeof(size_t));
char* temp = new char[len+1];
iFile.read(temp, len);
temp[len] = '';
Name = temp;
delete [] temp;

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...