Tutorial :Can't write a binary file



Question:

I have the following piece of code in C++.

int arr[] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};  ofstream output("Sample.txt", ios::out | ios::binary);    for(int i = 0; i < 10; i++)  {    output<<arr[i];  }  

Now the Sample.txt is like this:

12345678910  

Isn't the "Sample.txt" supposed to be in binary? Why doesn't it convert everything into binary when i opened the stream in binary mode. What should I do, incase i need binary of every element in the array and then print it to the file.


Solution:1

Isn't the "Sample.txt" supposed to be in binary?

No. What std::ios::binary does is to prevent things like the translation of '\n' from/to the platform-specific EOL. It will not skip the translation between the internal representation of the data bytes and their string translation. After all, that's what streams are all about. (Also, think of how you would stream an object of a user-defined type containing pointers in a binary representation.)

To actually write objects binary use std::ostream::write(). Beware, though, the result is platform-specific.


Solution:2

Binary mode mostly means that (for example) there won't be a transformation between a new-line character that you program writes, and whatever your platform thinks marks the end of a line (e.g. "\r\n" on Windows, "\r" on the Ma).

To actually write binary, you'd typically use ofstream.write().


Solution:3

Binary just means that newline characters are not converted to/from the OS-specific format. Outputting a value of type int with ofstream will format it as decimal number (normal ASCII text).

For what you mean by binary, you should rather write values of type char or use the non-formatting function output.write (docs here).


Solution:4

Binary as in 'not text' means that no formatting is done like new lines and so on.

See:

File streams opened in binary mode perform input and output operations independently of any format considerations. Non-binary files are known as text files, and some translations may occur due to formatting of some special characters (like newline and carriage return characters).

It will not translate for you to 0 and 1 format. Everything on pc is using binary format but when you open file and read it with editor, editor reads binary data and displays ASCII characters for you.


Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Previous
Next Post »