How to use Binary (not Text) I/O on the PC

You do not want the operating system to "help" you by automatically converting end-of-line indicators into "standard" end-of-line indicators. End-of-line indicators vary by platform.
Platform End-of-line indicator
  Description ASCII char decimal
Unix linefeed (newline) character LF \n 10
Macintosh carriage return character CR \r 13
Windows two character sequence CR LF \r\n 10,13
When in text mode on Windows, if the operating system detects what would be a normal end-of-line indicator from a different system (say, Linux), it will convert that indicator into the two-character CR LF sequence. Unfortunately, when dealing with binary files, this can result in an extra byte being inserted (during input or output) which could cause chaos. Accordingly, unless you are dealing with files for which you do not care if the end-of-line indicators are silently modified, you will want to do I/O in binary mode.

This is certainly true when the input is coming from a file. However, if input is coming from stdin and if stdin is coming from the console keyboard then it should not be opened in binary mode, because that has the side effect of switching stdin into raw mode in which all characters are read one by one with no echo, and Ctrl-C and Ctrl-Z are disabled so you cannot signal EOF.

An implementation using old C code is shown below.

    FILE *fp;
    char *filename;

    if (filename == "") {
        fp = stdin;
#ifdef _WIN32
#ifndef O_BINARY
#define O_BINARY 0
	if (isatty( fileno(stdin) ) == 0)
		setmode(fileno(stdin), O_BINARY);
        fp = fopen( filename, "rb");
    if (fp == NULL) {
        fprintf(stderr,"Cannot open file %s\n", filename);

Last modified: May 22, 2014