Input/Output from external file in C/C++, Java and Python for Competitive Programming | Set 2
Last Updated :
19 May, 2017
Improve
Prerequisites : Input/Output from external file in C/C++, Java and Python for Competitive Programming
In above post, we saw a way to have standard input/output from external file using file handling. In this post, we will see a very easy way to do this. Here we will compile and run our code from terminal or cmd using input and output streams.
CPP
Input from input.txt:
Windows Environment
For Windows, it's the case of redirection operators to redirect command input and output streams from the default locations to different locations.- Redirecting command input (<) : To redirect command input from the keyboard to a file or device, use the < operator.
- Redirecting command output (>) : To redirect command output from the Command Prompt window to a file or device, use the > operator.
a.exe < input_file > output_file
// A simple C++ code (test_code.cpp) which takes
// one string as input and prints the same string
// to output
#include <iostream>
using namespace std;
int main()
{
string S;
cin >> S;
cout << S;
return 0;
}
GeeksForGeeksCompile & run:
g++ test_code.cpp a.exe < input.txt > output.txtOutput in output.txt:
GeeksForGeeks
Linux Environment
I/O Redirection in linux: Input and output in the Linux environment are distributed across three streams. These streams are:- standard input (stdin): The standard input stream typically carries data from a user to a program. Programs that expect standard input usually receive input from a device, such as a keyboard, but using < we can redirect input from the text file.
- standard output (stdout): Standard output writes the data that is generated by a program. When the standard output stream is not redirected, it will output text to the terminal. By using > we can redirect output to a text file.
- 3. standard error (stderr): Standard error writes the errors generated by a program that has failed at some point in its execution. Like standard output, the default destination for this stream is the terminal display.
- > - standard output
- < - standard input
- 2> - standard error
- >> - standard output
- << - standard input
- 2>> - standard error
g++ file_name.cppRun the code
./a.out < input_file > output_fileWe can similarly give standard input/output from text files for C or Java by first compiling the code and while running the code we give input/output files in given format. For languages like python which don't require compilation, we do the following
python test_code.py < input.txt > output.txtRelated Article: Python Input Methods for Competitive Programming References :