Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

c++ Reading string from binary file using fstream

Tags:

c++

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;
}
like image 919
user3591225 Avatar asked Mar 11 '26 09:03

user3591225


1 Answers

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] = '\0';
Name = temp;
delete [] temp;
like image 96
R Sahu Avatar answered Mar 13 '26 21:03

R Sahu