简体   繁体   中英

Writing text to binary file - what's the difference?

I'm learning to write binary files in C++. I'm a bit confused with the result. Let's say I have this code:

#include<fstream>
#include<string>
using namespace std;

int main(){
    ofstream file;
    string text = "Some text over here";

    file.open("test.bin",ios::out|ios::binary);
    file.write(text.c_str(), text.length());
    file.close();

    return 0;
}

I'm expecting the output file test.bin to be "in binary", but when I look at it in notepad, I see normal text:

Some text over here

Is my expectation wrong? What makes things binary and what should I use to achieve it?

The most "important" definition of what the word "binary" means comes from just a situation where a number can take on one of two values. Whatever you call those doesn't strictly matter ("on"/"off", "1"/"0", "yes"/"no"). All that matters is that there are just two states.

Keep that core definition in mind. But you will find a large number of other idiomatic usages of the word "binary" in the computer world, depending on context.

As an example: Some people will refer to a file representing an executable image (such as an .EXE file on Windows) as simply "a binary" or ( "the binary" , when compiling a certain codebase and you know what executable you'd be talking about.)

You've tripped across another confusing distinction of how sometimes people will talk about a file format as being either "textual" or "binary". Yet today's computers are based on systems that are always binary ( technically they don't have to be ) . So if "textual" files aren't stored ultimately as binary bits somewhere, how else would they be stored? :-/

So really what it means for a file format to be labeled as "textual" is to say that it is "stricter about what binary patterns it uses, such that it will only use those patterns which make sense in certain textual encodings". That's why those files look readable when you load them up in text editors.

So a "textual file format" is a subset of all "file formats". And sometimes when people want to refer to something that is not in that subset of textual files, they will call it a "binary file format".

Plenty of room for confusion! But the upshot is that all you do when you open a file in "textual" vs. "binary" mode in C++ is to tell the stream that you are not using only the bit patterns likely to look good in a text editor when loaded. Opening in binary asks for all bytes to be sent to the file verbatim , instead of having it try and take care of cross-platform text-file differences in newline handling "under the hood" as a convenience.

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