C Study Guide

St. Gabriel's College

|

File Input/Output

In this lesson, we'll learn how to make our programs read and write files. This is very important if you want to let users open and save files with your program.

We use File Pointers to talk about files like variables.

FILE *r_file, *w_file;

Opening an Closing Files

We open files with fopen() and close them with fclose() when we've finished using them:

r_file = fopen("Readable.txt", "r");
w_file = fopen("Writeable.txt", "w");
...
fclose(r_file);
fclose(w_file);

fopen() has 2 parameters: The file name and the file permission. The file permission tells our program what we can do with the file. There are six options:

It's also very important to check that your file opened correctly. If it did not, it will cause an error later. To prevent errors, we will close the program with exit():

r_file = fopen("Readable.txt", "r");
if(r_file==NULL) {
    printf("Cannot open file.");
    exit(0);
}

File I/O

We use fgets() to read from a file, and fprintf() to write to the file.

fgets(string,1000, r_file); // file -> string
fprintf(w_file, "Hello File!");

for Loops are The Right Tool for The Job when you want to read/write a file or work with an array.

for(i=0; !feof(r_file); i++)
    fgets(line[i], 1000, r_file);

The function feof() tells us if we are at EOF (End Of File).

There are a number of other File I/O functions you may find useful: (For fread() and fwrite() you need to know how pointers work)