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!

8
  • 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. Commented Jun 3, 2012 at 19:49
  • @Mark a quick search revealed: cplusplus.com/reference/string/string Commented Jun 3, 2012 at 19:50
  • 1
    Post some real, copy-pasted code, please. Assuming string is std::string, this won't compile: string *text = "Text"; Commented Jun 3, 2012 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). Commented Jun 3, 2012 at 19:52
  • 2
    @BillJames - "a quick search" does not help here, as this string could be anything, not necessarily std::string. Commented Jun 3, 2012 at 20:02

7 Answers 7

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).
Sign up to request clarification or add additional context in comments.

1 Comment

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);
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.

Comments

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;

Comments

1

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

1 Comment

Assuming it is std::string. The string is being used in a pretty weird way.
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

2 Comments

We appreciate your answer but this is a 5 year old question.
@Sandeesh I think this shouldn't matter as long as the answer is in a "okay-ish" format, which it is, from my point of view
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.

Comments

-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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.