Redirecting standard IO
Moderator: Board moderators
Redirecting standard IO
Could you tell me how to use the ONLINE_JUDGE symbol in C++ in order to test my program using file input and file output. In other words I need the C++ equivallent code of the following C code:
[c]
#ifndef ONLINE_JUDGE
close (0); open ("myprog.in", O_RDONLY);
close (1); open ("myprog.out", O_WRONLY | O_CREAT, 0600);
#endif
[/c]
[c]
#ifndef ONLINE_JUDGE
close (0); open ("myprog.in", O_RDONLY);
close (1); open ("myprog.out", O_WRONLY | O_CREAT, 0600);
#endif
[/c]
I'm usually running my programs from command-line giving file as input stream:
It works in win/dos, if I'm correct it will work on linux too.
Ivor
Code: Select all
progname <inputfile
Ivor
There is a theory which states that if ever anyone discovers exactly what the Universe is for and why it is here, it will instantly disappear and be replaced by something even more bizarre and inexplicable.
-
- Guru
- Posts: 584
- Joined: Thu Jun 19, 2003 3:48 am
- Location: Sanok, Poland
- Contact:
It works with Linux as well. It's a surprise - I always used but your form is shorter, so I'm going to switch 
Code: Select all
cat input|progname

i discovered that a couple of days ago. I needed to dump the program output to a file, and as I'm not a linux user I just tried '>filename'... it worked, so I supposed '<filename' would also work. good to hear it works 

There is a theory which states that if ever anyone discovers exactly what the Universe is for and why it is here, it will instantly disappear and be replaced by something even more bizarre and inexplicable.
here is it:
for reading from file:
and for writing in file:
just add these two lines before ur program ( in main method )
for reading from file:
Code: Select all
freopen("input file name", "rt", stdin);
Code: Select all
freopen("output file name", "wt", stdout);
That would still be the C way of doing it. If you're using C++ iostreams, you can write like this (though there may be a simpler way?):
(And as long as it's for programming contest purposes, there's no reason to worry about freeing the created streams in the end.)
But I say I definitely recommend doing it Ivors way, redirecting the I/O from/to file with "<" and ">". That way you don't have to clutter up your code more than necessary.
Code: Select all
#include <fstream>
cin.rdbuf((new ifstream("___.in"))->rdbuf());
cout.rdbuf((new ofstream("___.out"))->rdbuf());
But I say I definitely recommend doing it Ivors way, redirecting the I/O from/to file with "<" and ">". That way you don't have to clutter up your code more than necessary.
my flavor:
Code: Select all
std::filebuf in, out;
std::cin.rdbuf(in.open("stdin.txt", std::ios_base::in));
std::cout.rdbuf(out.open("stdout.txt", std::ios_base::out));