13

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!

Keng92pd
  • 141
  • 1
  • 1
  • 4
  • It looks like you're writing the string object data, but that probably doesn't write the the TEXT stored in the object. You should be using Streams in C++. The equivalent to outfile << text. – billjamesdev Jun 03 '12 at 19:49
  • @Mark a quick search revealed: http://www.cplusplus.com/reference/string/string/ – billjamesdev Jun 03 '12 at 19:50
  • 1
    Post some real, copy-pasted code, please. Assuming `string` is `std::string`, this won't compile: `string *text = "Text"; ` – jrok Jun 03 '12 at 19:51
  • 2
    There is a lot wrong here, in basic understanding of how C++ works. You seem like a C programmer who's trying to make C++ things work. You should stop and read a book on C++. And most importantly, realize that C++ is a different animal (one you should almost never use `malloc` with). – Nicol Bolas Jun 03 '12 at 19:52
  • Does this even compile? : `string* test = "Text";` http://ideone.com/TcqhP – hmjd Jun 03 '12 at 19:54
  • @hmjd: No, it doesn't. Any compiler that accepts it is broken beyond repair. – Nicol Bolas Jun 03 '12 at 20:01
  • 2
    @BillJames - "a quick search" does not help here, as this `string` could be anything, not necessarily `std::string`. – Kiril Kirov Jun 03 '12 at 20:02
  • Possible duplicate of [c++ - properly writing std::string to binary file](https://stackoverflow.com/questions/27523273/c-properly-writing-stdstring-to-binary-file) – Hcorg Jun 01 '17 at 16:57

7 Answers7

13

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).
Elalfer
  • 5,312
  • 20
  • 25
Pablo Alvarez
  • 154
  • 1
  • 5
  • 4
    This worked for me with one change. In the writing code, I changed outfile.write(&str[0],size); to outfile.write(str.c_str(),size); – Scott Hutchinson Mar 14 '18 at 16:55
12

the line

outfile.write((char*) &text, sizeof (string));

is not correct

sizeof(string) doesn't return the length of the string, it returns the sizeof the string type in bytes.

also do not cast text to char* using a C cast, you can get hold of the char* by using the appropriate member function text.c_str()

you can simply write

outfile << text;

instead.

AndersK
  • 35,813
  • 6
  • 60
  • 86
3
  • Why are you using pointers to std::string class?
  • You should not use sizeof with std::string, as it returns the size of the std::string object, and not the real size of the string inside.

You should try:

string text = "Text";
outfile.write(text.c_str(), text.size());

or

outfile << text;
Jaideep Shekhar
  • 808
  • 2
  • 7
  • 21
Baget
  • 3,318
  • 1
  • 24
  • 44
1

Should probably also use c_str() to get the char pointer too, instead of that straight crazy cast.

Botz3000
  • 39,020
  • 8
  • 103
  • 127
Bryan
  • 11
  • 1
0

Your code is wrong wrong way you are using to write & read the file and file extension error you are trying to read text file .txt correct code

Write to file

std::string text = "Text";
ofstream outfile("myfile.dat", ofstream::binary | ios::out);
outfile.write(&text,sizeof (string));//can take type
outfile.write(&text,sizeof (text));//can take variable name
outfile.close();

reading file

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

Try This it will work

Shahzaib Chadhar
  • 178
  • 1
  • 10
0

I had the same problem. I found the perfect answer here: Write file in binary format

Key issues: use string::length to get the length of the string when writing out and use resize() before reading the string. And both for reading and writing, use mystring.c_str() instead the string itself.

-1

Try this code snippet.

/* writing string into a binary file */

  fstream ifs;
  ifs.open ("c:/filename.exe", fstream::binary | fstream::in | fstream::out);

  if (ifs.is_open())
  {
   ifs.write("string to binary", strlen("string to binary")); 
   ifs.close();
  }

Here is a good example.

Mutantoe
  • 703
  • 8
  • 20
PTT
  • 526
  • 7
  • 27