Is there anything in python that can replicate the functionality of freopen() in C or C++? To be precise, I want to replicate the functionality of:
freopen("input.txt","r",stdin);
and
freopen("output.txt","w",stdout);
And then use the same (standard) functions for console I/O for file I/O. Any ideas?
The freopen() function opens the new file associated with stream with the given mode, which is a character string specifying the type of access requested for the file. You can also use the freopen() function to redirect the standard stream files stdin , stdout , and stderr to files that you specify.
freopen("input.txt", "r", stdin); and freopen("output.txt", "w", stdout) are C library function calls that reuse stdin and stdout standard input and standard output stream file pointers as file pointers to the files input.txt and output.txt , respectively.
freopen() prototypeThe freopen function first attempts to close the file opened using stream . After the file is closed, it attempts to open the filename specified by the argument filename (if it is not null) in the mode specified by the argument mode . Finally it associates the file with the file stream stream .
Try this:
import sys
sys.stdin = open('input.txt', 'r')
sys.stdout = open('output.txt', 'w')
Text files are self explanatory. You can now run this code on Sublime Text or any other text editor.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With