I/O Streams

Delve into the input/output methods provided by the C standard library and learn how to interact with the command-line terminal.

Streams in C

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. Here are some examples of how standard input and standard output streams are used:

  • When we interact with a C program in a terminal, and type values in to pass to the program, we are using standard input.

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

  • When our program uses printf (see below) to print to the screen, we are using standard output.

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

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

Character I/O: getchar and putchar

When we want to read data a single character at a time, we can use the function getchar. The output function putchar writes 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