简体   繁体   中英

c++ Writing binary to a file

HI im trying to write to a txt file in binary.
now i wrote this code:

#include <iostream>
#include <fstream>
using namespace std;
int main()
{
    char* f = "abc";
    ofstream ofile("D:\\foobar.txt", ios_base::out | ios_base::binary);
    ofile.write(f, sizeof(char*));
    return 0;
}

now it writes "abc" but not in binary.
can someone please tell me how to write it in binary.

First of all, you write the wrong size and might go out of bounds. Use strlen instead to get the length of the string.

Secondly, think about how a letter like 'a' is stored in memory in the computer. It's is stored in whatever encoding the compiler and operating system uses, which is most likely ASCII . When you write that letter to a file it will write the value stored in memory to the file, and if you read the file using a program which is able to decipher the encoding it will show you the letter.

I'm just guessing here, but I think you expected binary format to write actual ones and zeroes as text. Well you do write ones and zeroes, not as text but as individual bits. And when all those bits are put together into bytes you get the bytes as they are stored in memory. If you look at the file in a hex-editor you will the the actual values, and you might even be able to find a program that shows you the actual binary values as ones and zeros.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM