code for File I/O


how do I start?

a.Declare a variable of type FILE*
b.Use fopen() to open the file named “ints.dat” for read access
c.Read all ints from the file calculating
i.The number of integers read
ii.The sum of the integers read
iii.The largest integer read
iv.The smallest integer read
d.Calculate the average of all integers in the file
e.Output all stats calculated in 2.c above and output the average of the integers with 4
decimal places.

Use Shell input redirection

Assume that the input will be made from console. (Using “cin” or “scanf”). It would be better to explain that with an example. Suppose the format of input is as follows:

First line contains an integer ‘n’, which is the number of numbers which are about to follow. Then in the next n lines, the n numbers are written. (Numbers may be space separated. It doesn’t make a difference in the source code. Do try it out.)

Following chunk of C++ code will be used to read this input.

int n;
cin >> n;
int *ar = new int[n];
for(int i=0; i<n; i++)
   cin >> ar[i];

Suppose the source code is saved in a file named “test.cpp”. Compile it from shell using the following command.

g++ test.cpp -o test.exe

(The .exe format is for windows, may be different for other operating systems)

Now, you can either run the executable from shell and feed in the input there itself (STDIN), OR you can redirect the input from a file using the following command.

test.exe < ints.dat

“ints.dat” is the name of the file from which input is to be taken, may be any other file name.

This will be read the input in the same way as is expected to be read from STDIN.
Redirecting the output to a file can also be done similarly using the ‘>’ operator. Go through the following link to read about redirecting output.

An easier way to perform file input/output is to use freopen().
In your case c code would be:

scanf("%d%d%d%d",&a,&b,&c,&d);//a,b,c,d are the four integers

printf(“The sum is %d\n”,(a+b+c+d));//for sum

Here is the link where you can find more about freopen():
link text

You need to save the file(ints.dat in this case) in the directory in which you are saving other c/c++ program.

1 Like