Page 1 of 1

Redirecting standard IO

Posted: Wed Sep 24, 2003 2:22 am
by BiK
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]

Posted: Wed Sep 24, 2003 9:33 am
by Subeen
you can use the freopen() function to test your programs.

Posted: Wed Sep 24, 2003 2:00 pm
by Ivor
I'm usually running my programs from command-line giving file as input stream:

Code: Select all

progname <inputfile
It works in win/dos, if I'm correct it will work on linux too.
Ivor

Posted: Wed Sep 24, 2003 3:55 pm
by Krzysztof Duleba
It works with Linux as well. It's a surprise - I always used

Code: Select all

cat input|progname
but your form is shorter, so I'm going to switch :-)

Posted: Wed Sep 24, 2003 8:37 pm
by Ivor
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 ;)

Posted: Thu Sep 25, 2003 4:23 am
by BiK
Hi Subeen. You mean to replace the open function with freopen or what? Could you type the actual C++ code. I know nothing about freopen. And I want to run my programs under Windows.

Posted: Thu Sep 25, 2003 5:47 am
by Subeen
here is it:
for reading from file:

Code: Select all

freopen("input file name", "rt", stdin);
and for writing in file:

Code: Select all

freopen("output file name", "wt", stdout);
just add these two lines before ur program ( in main method )

Posted: Thu Sep 25, 2003 8:04 am
by Per
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?):

Code: Select all

#include <fstream>

cin.rdbuf((new ifstream("___.in"))->rdbuf());
cout.rdbuf((new ofstream("___.out"))->rdbuf());
(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.

Posted: Thu Sep 25, 2003 5:38 pm
by BiK
Thanks guys. Now everything is OK.

Posted: Sat Apr 10, 2004 3:22 pm
by macin
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));