Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Writing a string to file in binary mode

So I'm using this code to write the file(just testing now, I'm going to write a level editor later):

 
int main()
{
    ofstream file("level.bin", ios::binary);
    int ents = 1; //number of entites
    file.write((char*)&ents, sizeof(int));
    float x = 300; //x and y coords
    float y = 500;
    file.write((char*)&x, sizeof(float));
    file.write((char*)&y, sizeof(float));
    int imglength = 12; //strings are prefixed by a length
    file.write((char*)&imglength, sizeof(int));
    string img = "platform.png"; //string
    file.write(img.c_str(), sizeof(img.c_str()));
    cout << "wrote\n";
    return 0;
}

The code I'm using to load it is this:

 

void SceneManager::LoadScene(std::string filename) { std::ifstream file(filename.c_str(), std::ios::binary); int ents; file.read((char*)&ents, sizeof(int)); std::cout << ents << std::endl; for(int i = 0; i < ents; i++) { //read x and y coords float x; float y; file.read((char*)&x, sizeof(float)); file.read((char*)&y, sizeof(float)); std::cout << x << " " << y << std::endl; int imglength; file.read((char*)&imglength, sizeof(int)); std::cout << imglength << std::endl; std::stringstream ss; for(int k = 0; k <= imglength; k++) { //read string char c; file.read((char*)&c, sizeof(char)); ss << c; } std::string image = ss.str(); std::cout << image << std::endl; phys_static ent; Def edef; edef.SetVal("x", x); edef.SetVal("y", y); edef.SetString("image", image); ent.init(edef); AddEntity(ent); } file.close(); }

Everything works fine except the string loading. I expect I'm writing it wrong, as instead of the platform.png it shows plattttttttt and errors out when I load the image. I'm also prefixing the string with it's length. What is the correct way to write a string to a binary file? What is the corre

like image 208
Chris Avatar asked Mar 26 '11 14:03

Chris


1 Answers

The error is at this line:

file.write(img.c_str(), sizeof(img.c_str()));

What you want is:

file.write(img.c_str(), img.size());

The sizeof(img.c_str()) returns 4 because sizeof(char *) (the return type of c_str()) is 4 on your platform. This means first 4 characters are written and then you get just some garbage.

like image 112
Karel Petranek Avatar answered Oct 13 '22 00:10

Karel Petranek