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.
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 .
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 .
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With