I/O Streams

Now, we'll delve into the input/output methods provided by the C standard library and see how we can interact with the command-line terminal.

The standard C library (linked to using #include <stdio.h>) includes a handful of functions for performing input and output in C.

C and UNIX make use of a concept called streams in which data can be sent and received between programs, devices, and the operating system. We can distinguish between two types of streams: text and binary.

Text streams are made up of lines, where each line has zero or more characters, and is terminated by a new-line character \n. Binary streams are more “raw” and consist of a stream of any number of bytes.

C programs all have three streams “built-in”: standard input, standard output, and standard error. When you interact with a C program in a terminal, and you type values in, you are using standard input.

UNIX has a concept called pipes (e.g. see here) whereby you can redirect any stream (e.g. output from some program or device) as input to another process (e.g. your program). When you redirect a stream to your program, which takes it in as input, you are using the standard input stream.

When your program uses printf() (see below) to print to the screen, you are using standard output.

Files (e.g. data files) are also associated with streams, and we will see below how to read from them and write to them.

We won’t talk about standard error here. Refer to a UNIX reference, a C book, or Streams and Files for more details.

Character I/O: getchar() and putchar()

When you want to read data a single character at a time, you can use getchar(). The output function putchar() will write out one character at a time to standard output.

Create a free account to access the full course.

By signing up, you agree to Educative's Terms of Service and Privacy Policy