use of freopen

many people uses this code snippet in C++(4.3.2). What is _MSC_VER and Why do we need to use freopen? what happens if we skip this piece of code. Also what benifits us by using this? Kindly reply.

#ifdef _MSC_VER
	freopen("input.txt","r",stdin);
#endif

If someone compiles such code with _MSC_VER macro defined, he/she reads input from input.txt file instead on stdin. Probably used for testing…

When submitted to CodeChef, _MSC_VER is not defined, so the input is read from stdin…

2 Likes

Adding one more point to @betlista’s answer.

You might have / would come across

#ifndef ONLINE_JUDGE
   //something, maybe take input from some file
#endif

These are for testing purposes, so that you store the sample test cases in a file and you run your code to see the output without having to type the sample inputs again and again during debugging.

You can also use redirection.

After compilation, with the executable file if you write

:~$ a.out < test.in > test.out

It will take input from test.in file and will write the output to test.out

You can ignore these here in the beginning, but you must learn these as some contests do ask for the output file e.g. GCJ

2 Likes

Yes, debugging is good point, in my gdb redirection is not working, but most of time I prefer logging comparing to debugging…

2 Likes