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.

z
a
cat
vwsdf

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

#include<stdio.h>


char str[5];

void print()
{
  printf("%s\n",str);
}

int main() {

	freopen("input.txt", "r", stdin);

	while (scanf("%s",str) > 0) {
		print();
	}

	return 0;
}
#gcc sample.c -osample
#./sample

Output:

z
a
cat
vwxyz

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++

#include <iostream>
#include<stdio.h>
using namespace std;

#define N 10

char str[5];

void print()
{
  cout << str << endl;
}

int main() {

	freopen("input.txt", "r", stdin);

	while (cin>>str) {
		print();
	}

	return 0;
}

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

   while (cin >>
x) { . . . }

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

Ref:

http://www.fredosaurus.com/notes-cpp/io/io-operators.html



Related Contents to follow