Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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

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

1 Answer

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;

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...