Skip to main content

Section 15.2 Reading from a File

This program demonstrates how to open a file, read numbers from the file and then close the file.
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:
9  56  3  8  -11  0  -45  55  2  78

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);
}

Subsection 15.2.1 Your 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.

Activity 15.2.

Use the code window below to find that average!

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);
}