Binary Streams (The GNU C Library)

### 12.17 Text and Binary Streams ¶

GNU systems and other POSIX-compatible operating systems organize all files as uniform sequences of characters. However, some other systems make a distinction between files containing text and files containing binary data, and the input and output facilities of ISO C provide for this distinction. This section tells you how to write programs portable to such systems.

When you open a stream, you can specify either a text stream or a binary stream. You indicate that you want a binary stream by specifying the ‘`b`’ modifier in the opentype argument to `fopen`; see Opening Streams. Without this option, `fopen` opens the file as a text stream.

Text and binary streams differ in several ways:

- The data read from a text stream is divided into lines which are terminated by newline (`'\n'`) characters, while a binary stream is simply a long series of characters. A text stream might on some systems fail to handle lines more than 254 characters long (including the terminating newline character).
- If the system does not use POSIX-style in-band signalling to indicate line termination, it can be impossibe to write anything to a text stream without adding a line terminator. As a result, flushing a text stream (by calling `fflush`, for example) may produce a logical line terminator even if no `'\n'` character was written by the program.
- Text files may contain lines that embed `'\n'` characters that are not treated as line terminators by the system. C programs cannot read such text files reliably using the `stdio.h` facilities.
- On some systems, text files can contain only printing characters, horizontal tab characters, and newlines, and so text streams may not support other characters. However, binary streams can handle any character value.
- Space characters that are written immediately preceding a newline character in a text stream may disappear when the file is read in again.
- More generally, there need not be a one-to-one mapping between characters that are read from or written to a text stream, and the characters in the actual file.

Since a binary stream is always more capable and more predictable than a text stream, you might wonder what purpose text streams serve. Why not simply always use binary streams? The answer is that on these operating systems, text and binary streams use different file formats, and the only way to read or write “an ordinary file of text” that can work with other text-oriented programs is through a text stream.

In the GNU C Library, and on all POSIX systems, there is no difference between text streams and binary streams. When you open a stream, you get the same kind of stream regardless of whether you ask for binary. This stream can handle any file content, and has none of the restrictions that text streams sometimes have.