Binary files

Hello. I was recently learning about files in C++ and I came across binary files. What is the difference between binary files and regular files, and when should I use them? Thanks for answering.
The quick answer is that the difference is simply how you open the file in c++ (ios::binary added to file.open()) and the tools you can use on it (read() vs getline() for example).


text files are a subset of binary files, containing only text, which if in an 8 bit text format like ascii implies that only the printable characters are in it. Binary files tend to have every possible byte value for any given byte as a possible data value. Its best to just stick with the 'how you want to open it' answer, as trying to define gets really muddy (consider Unicode where unprintable ascii bytes will appear in the data but it represents readable text data).

another way to say it,
you have a file with 4 bytes in it. it represents the value 1234 as an integer.
that will either be in binary as 0x000004D2 represented by unprintable characters and gibberish if opened with notepad or 1234 as human readable text. Its easy to see why this is useful for 16535 as a 2 byte integer. Its 5+ (space, comma, something added for multiple data points in text) bytes as text and exactly 2 as binary, so if you had a file with a million values, … its a lot less space.
Last edited on
If you mean the difference between opening a file in "text" or "binary" mode, then the difference depends on the operating system. For example, in Linux there's no difference at all, but in Windows text mode will automatically convert the "\r\n" line-ending to "\n" on input and do the opposite on output. I don't know how Unicode enters into it, though, so it may be more complicated these days (multi-byte to wide-char, for instance).

And I think there used to be something about the ctrl-Z character (ascii 26) marking the end of the file in Windows (DOS, maybe?). You could actually "hide" stuff after the ctrl-z in the file. I doubt that works anymore.
it may. copy con … still expects ctrlz to end it. unclear if you can still do hax with that. I doubt any modern word processor would stop hard on the ctrl z .. in fact we know most don't as opening a binary file in them gives all the junk, not just to the first random 26 it finds. But stuff like console operations may still respect it, like type x.txt > y.txt

Last edited on
Topic archived. No new replies allowed.