Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

write and read string to binary file C++

Im having problems writing string into a binary file. This is my code:

ofstream outfile("myfile.txt", ofstream::binary);
std::string text = "Text";
outfile.write((char*) &text, sizeof (string));
outfile.close();

Then, I try to read it,

char* buffer = (char*) malloc(sizeof(string));
ifstream infile("myfile.txt", ifstream::binary);    
infile.read(buffer, sizeof (prueba));
std::string* elem = (string*) buffer;
cout << *elem;
infile.close();

I just cant get it to work. I am sorry, I am just desperate. Thank you!

like image 309
Keng92pd Avatar asked Jun 03 '12 19:06

Keng92pd


1 Answers

To write a std::string to a binary file, you need to save the string length first:

std::string str("whatever");
size_t size=str.size();
outfile.write(&size,sizeof(size));
outfile.write(&str[0],size);

To read it in, reverse the process, resizing the string first so you will have enough space:

std::string str;
size_t size;
infile.read(&size, sizeof(size));
str.resize(size);
infile.read(&str[0], size);

Because strings have a variable size, unless you put that size in the file you will not be able to retrieve it correctly. You could rely on the '\0' marker that is guaranteed to be at the end of a c-string or the equivalent string::c_str() call, but that is not a good idea because

  1. you have to read in the string character by character checking for the null
  2. a std::string can legitimately contain a null byte (although it really shouldn't because calls to c_str() are then confusing).
like image 98
Pablo Alvarez Avatar answered Oct 05 '22 23:10

Pablo Alvarez