Redirection from and to Files

Saving Output to a File

There are cases where we want to save the output of our program to a file. The simple way is to highlight and copy things from the command line, paste it in notepad, and save the file. But there’s an easier and more precise way to do it. Use the > symbol.

To be precise, if we want to save the output of the program executable to a file called output.txt, we type the command ./executable > output.txt.

On windows, the command is executable.exe > output.txt. The reason it looks so similar is because Windows copied a lot of things from Unix, the ancestor operating system of Linux and Mac.

Try it yourself! Of course, you can change the output file name to anything you want and not just output.txt

It’s important to note at this point that this will completely erase the contents of the file you’re saving into, even if your program hasn’t printed anything out yet. So be careful!

Reading Input from a File

Another common case is when we have input from a file that we want our program to read in from instead of us having to type the values. Again, there’s a simple way to do that! Use the < symbol.

If we want to make the program executable read from a file called input.txt, we type the command ./executable < input.txt.

On windows, the command is executable.exe < input.txt.

Combining the Two

There are cases where we have input from a file and we want to save the output to another file. During the Google Code Jam, input files are downloaded from their website and you have to upload the correct output file. Or maybe you just want to store the output to a pre-determined input. The way you do that is just combining the two.

An example command that combines them is ./executable < input.txt > output.txt

Note that the command ./executable > output.txt < input.txt is just as valid and does exactly the same thing.

I’m sure the Windows users among you can get the pattern by now, so I won’t belabor the point.