Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can't write a binary file

Tags:

c++

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.

like image 418
Jay Avatar asked Mar 11 '10 21:03

Jay


People also ask

How do you write a binary file?

To write to a binary fileUse the WriteAllBytes method, supplying the file path and name and the bytes to be written. This example appends the data array CustomerData to the file named CollectedData. dat .

Is there Delimeter for binary file?

The binary delimiter to be inserted after the data from each message must be expressed as a comma-separated list of hexadecimal bytes, for example: x34,xE7,xAE .

Can any file be a binary file?

A binary file is any file stored on a computer or related media. Any and all computer data is stored in binary form — that is, it consists of ones and zeros. Computer files that have only textual information are simpler than other files, such as those that store images, for instance.


1 Answers

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.

like image 71
sbi Avatar answered Oct 14 '22 05:10

sbi