Question

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;
}
Was it helpful?

Solution

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;

OTHER TIPS

you need to create a buffer of char type.

char *buffer = new char[size];

Then use your buffer as the parameter to read function

iFile.read(buffer, size);

Instead of this

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

Try this:

Name.resize(StringLength);
iFile.read((char *)&Name[0], StringLength);

Your original line overwrites the string object data from the beginning, which may contain the string length and capacity, for instance, instead of the character data. Also you don't resize the string appropriately to be able to contain the data.

Conceptually, you need to understand the data stream which you are reading. Not everything use ASCII which uses a byte size of 8 bits. I also notice you did not set bit size read which can be as little as one bit to as large as {R, B, G, A} color set. Using your basic 2 dimensional reiteration structured code.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top