The streams stdout, stdin and stderr

Location
  1. Courses

    /

  2. Complete C++ Course

    /

  3. The C Standard Library

    /

  4. File IO

    /

  5. The streams stdout, stdin and stderr

The stream objects stdout, stdin and stderr

When a C/C++ program starts, three pointers of type FILE, named stdout, stdin and stderr are created. They are streams linked to the console. That is what was meant before when it was said that the structure FILE might represent a stream to something else than a file.

Since stdout, stdint and sterr are pointers to FILE structures, it is possible to use them with the same functions we used to input/output to files. However, stdout and stderr must be used for output operations and stdin for input operations.

That means that the following:

printf("Hello.");

Is equivalent to:

fprintf(stdout, "Hello.");

The difference between stdout and stderr is that stderr is used to output errors (If you had not guessed yet). Functions used to read/write to the console are basically the same as the functions to input/output to streams, except that they directly input/output to stdin without taking the stream as argument. To write to the console through stderr instead of stdin, we must use the functions to output to streams and give them stderr as argument.

stdout, stdin and sterr might not be linked to the console

When a program is called from a command line, it is possible to redirect its output/input operations to a file instead of the console.

For example, on GNU/Linux, with the bash command line interpreter, the following command will execute the program test and redirect its output operations to the file test.txt:

./test > test.txt

In that case, stdout is a stream linked to the file test.txt, so the command printf will actually output to a file. However, in that case, stderr is still linked to the console. The streams stdout and stderr are linked to 2 different output 'channels' of the console.

If stdout, stdin or sterr are redirected to a storage device, they are fully buffered. Otherwise, they might be either line buffered or not buffered at all depending on the compiler.

Note that it is possible to redirect the streams pointed by stdout, stdin and sterr to a file, from the code, by using the function freopen with them.