So I made an output file that does this:
ofstream outf;
outf.open(filename);
string str = "This is test!";
int lengthofstr = str.length();
outf.write((char*)&str, sizeof(lengthofstr));
outf.close();
After that has been completely, with another program (exe) I read in the file:
void readem(char* filename, ifstream &inf){
inf.open(filename);
string a;
if (inf.is_open()){
inf.read((char*)&a, sizeof(int));
cout << a << endl;
}
else
cout << "file is not opening!" << endl;
inf.close();
}
The c++ exe breaks as soon as i try to run it. Im trying to return the string. If someone could point me to a tutorial/post/question/ or explain to me how the ifstream read works, thank you ahead of time XD
You can't write a std::string
like this at all! The content of the file may contain the characters you expect it to include (because std::string
is likely to use the small string optimization) but for bigger string it won't: the std::string
object you are writing is just the "control record" of the actual string. To write a std::string
you'd probably write two pieces of information:
std::string
to be written.std::string
.The operations would look something like this:
write(stream, s.size());
write(stream, s.c_str(), s.size());
(the functions write()
suitably implement serialization of an integer value and a sequence of characters; just writing bytes is, in my opinion, not the way to go)
Merely writing the characters making up a std::string
object isn't any useful.
When reading bytes into the memory occupied by an std::string
object you get undefined behavior: the control record part of the string gets overwritten with some content which is unlikely to yield a valid object. Assuming the object is written as above, you could read it (assuming suitable deserializing functions read()
) using code like this:
std::string s;
s.resize(read<std::string::size_type>(stream));
read(stream, s.data(), s.size());