Input/Output from external file in C/C++, Java and Python for Competitive Programming - GeeksforGeeks

06 Jan, 2022
In Competitive Programming, most of the time we need to enter input for checking our code manually. But it would become cumbersome if we have a questions like Graphs, strings, or bulky entry of input data because it will definitely time out or the chances of typing incorrect data would be increased. We can easily get rid of problem by simply saving the test cases to the specified file at the desired location according to our easiness. These are useful in competitions like Facebook Hackercup, Google Codejam. These competitions do not provide the online judge like environment rather than they asked you to upload input and output files.For Input/Output, we basically use these two type of file access modes i.e.,  
“r”: It means read, as it opens the file for input operation but the file must exist at specified location.  
“w”: It means write, as it creates an empty file for output operations. If a file with the same name already exists, its contents are discarded and the file is treated as a new empty file.  
 
C/C++
In C/C++ we can use freopen for standard input and output. The syntax of this function as:-  
FILE * freopen(const char * filename, const char * mode, FILE * stream );
 
filename: It refers to name of the file that we want to open.
mode: Discussed above.
stream: Pointer to a FILE object that identifies the stream to be reopened.  
We can also use Symbolic constant ONLINE_JUDGE for debugging purpose. As most of the online judges add this flag at the end of the command line before executing our code. For example in C++11, it would be compiled as  
-std = c++0x -O2 -static -s -lm -DONLINE_JUDGE
So we can take advantage of that by using C preprocessor directive. 
we can also do the same using ONLINE_JUDGE in java, but as of now it does not work in codechef but works in codeforces. 
CPP
Java
// Below is C/C++ code for input/output#include<stdio.h> int main(){#ifndef ONLINE_JUDGE     // For getting input from input.txt file    freopen("input.txt", "r", stdin);     // Printing the Output to output.txt file    freopen("output.txt", "w", stdout); #endif    return 0;}
// Java code for I/Oimport java.io.*;// this does not works in codechef but works in codeforcesclass GFG {    public static void main(String[] args)        throws IOException    {        if (System.getProperty("ONLINE_JUDGE") == null) {            // Redirecting the I/O to external files             // as ONLINE_JUDGE constant is not defined which            // means             // the code is not running on an online judge             PrintStream ps                = new PrintStream(new File("output.txt"));            InputStream is                = new FileInputStream("input.txt");             System.setIn(is);            System.setOut(ps);        }    }}// This code is contributed by Rahul Mandal
JAVA
In Java, we can use BufferedReader class for the fast Input and PrintWriter class for formatted representation to the output along with FileReader and FileWriter class.  
FileReader(String filename): This constructor creates a new FileReader, and instructs the parser to read file from that directory. The file must exist in that specified location.
FileWriter(String fileName): This constructor creates a FileWriter object, to the specified location.
 
Java
// Java program For handling Input/Outputimport java.io.*;class Main{    public static void main(String[] args) throws IOException    {        // BufferedReader Class for Fast buffer Input        BufferedReader br = new BufferedReader(                               new FileReader("input.txt"));         // PrintWriter class prints formatted representations        // of objects to a text-output stream.        PrintWriter pw=new PrintWriter(new                BufferedWriter(new FileWriter("output.txt")));         // Your code goes Here         pw.flush();    }}// Thanks to Saurabh Kumar Prajapati for providing this java Code
PYTHON
In python we first import the module sys(system), after that We will use open() function which returns the file object, that are commonly used with two arguments: open(filename, mode).  
The first argument is a string containing the filename.
The second argument is another string (mode) containing a few characters describing the way in which the file will be used.
 
Python
# Below is Python code for input/output import sys# For getting input from input.txt filesys.stdin = open('input.txt', 'r') # Printing the Output to output.txt filesys.stdout = open('output.txt', 'w')
This article is contributed by Shubham Bansal. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. 
mandalrahul05
abhishek0719kadiyan
Competitive Programming
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Bits manipulation (Important tactics)
Breadth First Traversal ( BFS ) on a 2D array
Remove all occurrences of a character in a string | Recursive approach
Container with Most Water
How to begin with Competitive Programming?
Sequence Alignment problem
String hashing using Polynomial rolling hash function
Shortest path in a directed graph by Dijkstra’s algorithm
Formatted output in Java