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:
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.
#include <fstream>
#include <iostream>
usingnamespace 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 <constchar*> (&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.
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. :)