In this blog post we will know how to take inputs from file using freopen and scanf in c and c++ program. Taking inputs from file is a basic know how for competitive programming. We can also take inputs from file using cin and cout.

Let us assume we have to read inputs from file input.txt. The contents of input.txt are as follows.

How to take inputs from file using freopen and scanf ( sample code )

scanf function in c:

These subroutines return the number of successfully matched and assigned input items. This number can be 0(zero) if an early conflict existed between an input character and the control string. ( from scanf man )

freopen function in c:

he  freopen() function opens the file whose name is the string pointed  to by path and associates the stream pointed to by stream with it.  The original  stream  (if  it exists) is closed.  The mode argument is used just as in the fopen() function.  The  primary  use  of  the  freopen() function  is  to change the file associated with a standard text stream (stderr, stdin, or stdout).

Reading inputs  from file in c++

Because the >> operator returns the iostream (eg, cin), which can be tested for EOF or errors, the cin loop idiom can be used.

which effectively tests for EOF, and also that the input is a valid value.


Related Contents to follow