Binary file output

Jan 1, 2011 at 11:54pm
Hi everyone, I'm having a problem. I'm trying to save a string into a binary file using c++ library (iostream) and string type. But I keep saving a normal text file.
Here is the code:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#include <fstream>
#include <iostream>

using namespace std;

int main()
{
  string text;
  getline (cin,text);
  ofstream outbin("myfile.bin", ios::out | ios::binary);
  const char *temp = text.c_str();
  outbin.write(temp, text.length());
  outbin.close();
  return 0;
}


If the input text is for example, "Mundo!", the output file "myfile.bin" opened with the notepad looks like these:

Mundo!


Any suggestion will be great...and I'm sory for my bad english, since it's not my first language. Thanks.
Jan 2, 2011 at 1:10am
Wait... you are writing a textual string to file and expecting it to look like something else?

The only difference between a text file and a binary file is how some operating systems handle newline sequences.

That, and what people tend to write into them. Text files typically have stuff humans can read. Binary files typically don't. But if you write human-readable stuff to a "binary" file then you've still got a human-readable "textual" file.

Hope this helps.
Jan 2, 2011 at 1:21am
I think I understand what you are saying Duoas. But for example:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
#include <fstream>
#include <iostream>
using namespace std;

int main()
  {
  unsigned year = 974;

  // Save it as text
  ofstream outtxt( "textual.txt" );
  outtxt << year << flush;
  outtxt.close();

  // Save it as binary
  ofstream outbin( "binary.bin", ios::binary );
  outbin.write( reinterpret_cast <const char*> (&year), sizeof( year ) );
  outbin.close();

  return 0;
  }


In this code, which you have written in a topic last year you are saving the unsigned int as, what i think it is hexadecimal. Being the output of binary.bin:

ώ 


And of textual.txt:

974


I understand that when you write binary.bin you are writing the data in its binary representation instead of reading it as strings.
Last edited on Jan 2, 2011 at 1:40am
Jan 2, 2011 at 4:42am
I'm still not sure where you are getting confused, because you seem to have the concept correctly.

"974" is a string.
974 is an integer.

f << year outputs a string.
f.write( reinterpret_cast <const char*> (&year), sizeof( year ) ); outputs an integer.
Jan 2, 2011 at 2:49pm
Yes I've finally understood, I was confuse thinking that the strings were converted in same way in order to be save in a text file and then be read using a character set like unicode or ansi. Now I know that outputing a string into a binary file is nearly the same to doing so in a text file (same chars may be converted depending on the platform used, like the carriage returns).
Then I thank you. Is great to know that there is people of great knowledge willing to help the newbish. :)
Topic archived. No new replies allowed.