How do we know how many numbers are stored in the file? In this particular example, we are told that there are 10 numbers stored in the file. Later, we will learn how to figure this information out on our own. Here is what the file looks like:
Compile and run the code below in your own C environment.
#include <stdio.h>
int main(void) {
FILE *ifile; /* ifile is a variable name - you could use any other name here.
However, the '*' is important. We'll learn about it more later.
We call this a file pointer. */
int i, num, N;
ifile = fopen("my_first_file.txt", "r"); /* open file for reading.
The "r" stands for reading. */
N = 10; /* we were told that there are 10 numbers in the file */
for (i = 0; i<N; i++) {
fscanf(ifile, "%d", &num);
printf("I read %d from the file. \n", num);
}
fclose(ifile); /* closes the file */
return(0);
}
Subsection15.2.1Your Turn: Calculating the Average of the Numbers Read from the File
Now, suppose we wanted to find the average of the numbers read from the same file as above.
Compile and run the code below in your own C environment.
#include <stdio.h>
int main(void) {
FILE *ifile; /* ifile is a variable name - you could use any other name here.
However, the '*' is important. We'll learn about it more later.
We call this a file pointer. */
int i, num, N, sum;
N = 10; /* we are told there are 10 numbers in the file */
ifile = fopen("my_first_file.txt", "r"); /* open file for reading.
The "r" stands for reading. */
sum = 0;
for (i = 0; i<N; i++) {
fscanf(ifile, "%d", &num);
printf("I read %d from the file. \n", num);
sum += num;
}
fclose(ifile); /* closes the file */
printf("The sum of the numbers read is %d. The average is %.2f.", sum, (float) sum / N);
return(0);
}