Redirecting the Standard Input and Output Streams

In this lesson, we will learn how the standard inputs and outputs of programs can be redirected to files or piped to other programs.

All of the programs that we have seen so far have interacted through stdin and stdout, the standard input and output streams. Input and output functions like readf and writeln operate on these streams by default. While using these streams, we assumed that the standard input comes from the keyboard and that the standard output goes to the screen.

We will start writing programs that deal with files in the next lesson. We will see that, just like the standard input and output streams, files are character streams as well; they are used in almost the same way as stdin and stdout. But before seeing how files are accessed from within programs, we will get familiar with how the standard inputs and outputs of programs can be redirected to files or piped to other programs.

Using > to redirect standard output to file #

When starting the program from the terminal, typing a > character and a file name at the end of the command line redirects the standard output of that program to the specified file. Everything that the program displays to its standard output will be written to that file instead.

Let’s test this with a program that reads a floating point number from its input, multiplies that number by two and displays the result to its standard output:

Get hands-on with 1200+ tech skills courses.