Domanda

I have been having a very hard time writing to a binary file and reading back. I am basically writing records of this format

1234|ABCD|efgh|IJKL|ABC

Before writing this record, I would write the length of this entire record ( using string.size()) and then I write the record to the binary file using ofstream as follows:

int size;

ofstream studentfile;
studentfile.open( filename.c_str(),ios::out|ios::binary );
studentfile.write((char*)&size,sizeof(int));
     studentfile.write(data.c_str(),(data.size()*(sizeof(char))));
     cout << "Added " << data << " to " << filename << endl;
     studentfile.close();

And I read this data at some other place

ifstream ifile11;
     int x;
     std::string y;
     ifile11.open("student.db", ios::in |ios::binary);
     ifile11.read((char*)&x,sizeof(int));
     ifile11.read((char*)&y,x);
     cout << "X " << x << " Y " << y << endl;

first I read the length of the record into the variable x, and then read the record into string y. The problem is, the output shows x as being '0' and 'y' is empty.

I am not able figure this out. Someone who can look into this problem and provide some insight will be thanked very much.

Thank you

È stato utile?

Soluzione

You can't read a string that way, as a std::string is really only a pointer and a size member. (Try doing std::string s; sizeof(s), the size will be constant no matter what you set the string to.)

Instead read it into a temporary buffer, and then convert that buffer into a string:

int length;
ifile11.read(reinterpret_cast<char*>(&length), sizeof(length));

char* temp_buffer = new char[length];
ifile11.read(temp_buffer, length);

std::string str(temp_buffer, length);
delete [] temp_buffer;

Altri suggerimenti

I know I am answering my own question, but I strictly feel this information is going to help everyone. For most part, Joachim's answer is correct and works. However, there are two main issues behind my problem :

1. The Dev-C++ compiler was having a hard time reading binary files.

2. Not passing strings properly while writing to the binary file, and also reading from the file. For the reading part, Joachim's answer fixed it all.

The Dev-C++ IDE didn't help me. It wrongly read data from the binary file, and it did it without me even making use of a temp_buffer. Visual C++ 2010 Express has correctly identified this error, and threw run-time exceptions and kept me from being misled. As soon as I took all my code into a new VC++ project, it appropriately provided me with error messages, so that I could fix it all.

So, please do not use Dev-C++ unless you want to run into real troubles like thiis. Also, when trying to read strings, Joachim's answer would be the ideal way.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top