C++ fread() into a std::string

ali picture ali · Nov 28, 2012 · Viewed 17.5k times · Source

Like always, problems with pointers. This time I am trying to read a file (opened in binary mode) and store some portion of it in a std::string object. Let's see:

FILE* myfile = fopen("myfile.bin", "rb");
if (myfile != NULL) {
    short stringlength = 6;
    string mystring;
    fseek(myfile , 0, SEEK_SET);
    fread((char*)mystring.c_str(), sizeof(char), (size_t)stringlength, myfile);
    cout << mystring;
    fclose(myfile );
}

Is this possible? I don't get any message. I am sure the file is O.K. When I try with char* it does work but I want to store it directly into the string. Thanks for your help!

Answer

Potatoswatter picture Potatoswatter · Nov 28, 2012

Set the string to be large enough first to avoid buffer overrun, and access the byte array as &mystring[0] to satisfy const and other requirements of std::string.

FILE* myfile = fopen("myfile.bin", "rb");
if (myfile != NULL) {
    short stringlength = 6;
    string mystring( stringlength, '\0' );
    fseek(myfile , 0, SEEK_SET);
    fread(&mystring[0], sizeof(char), (size_t)stringlength, myfile);
    cout << mystring;
    fclose(myfile );
}

There are many, many issues in this code but that is a minimal adjustment to properly use std::string.