# I/O Redirection

• Many programs take input from the console (stdin) and print output to the console (stdout and stderr). For example, consider this simple program that asks the user for a name and then greets the user:

hello.cpp
#include <iostream>
using namespace std;

int main() {
cout << "Name: ";
string name;
getline(cin, name);
cout << "Hello, " << name << "!" << endl;
}
• In Terminal, we can compile and run this program with

./hello

We would have to type input ourselves and we would see the output in the console:

Name: Maxim
Hello, Maxim!
• However, we sometimes want our program to read input from a file instead of the console. In Terminal, we would execute something like this to use the contents of input.txt as input:

./hello < input.txt
• Similarly, we can redirect output of the program so some file, such as output.txt:

./hello > output.txt

After executing this command, output.txt will contain the output of the program. This file will be overwritten if it already exists or created if it does not exist.

• We can also combine input and output redirection in Terminal with

./hello < input.txt > output.txt