Lecture 20: Files

 

Output to File

Today we are going to learn how to read from files and write to file. As an example we will only learn how to read and write text files, files where the infomation is stored in ASCII format. Such files differ from binary format because they are also readable by humans. We already are using with text files, because all our programs written in the practical lessons are of this type.
These files can be placed on floppy disks, on the harddisk, or even on CD-ROMs (in which case they can - of course - only be read and not written).

Keywords

The following keywords are related to file access:
 
 FILE
 fopen()
 fclose()
 fscanf()
 fprintf() 
 feof()
 fputs() 
 fgets()
 fputc()
 fgetc()
These are defined in the library <stdio.h>, which we should therefore include in the beginning of our program.

Declaring a variable for file access:

Before we can open a file and have access to it (either reading or writing) we have to declare a so-called "handle" to it. This is a variable that stores information about the status of the file. In C we can declare a text file in the following way:
 
 FILE *filehandle

With filehandle the variable that will store the pointer to the information. This is NOT equal to the actual name of the file, as we will see in a moment. The place to declare this is together with the other variables.
Example:
  FILE *f;
This makes f a pointer to a file handle.
Without ever having to worry about it (no need to remember this),  the actual variable type FILE is
typedef struct{
  short          level;
  unsigned       flags;
  char           fd;
  unsigned char  hold;
  short          bsize;
  unsigned char *buffer, *curp;
  unsigned       istemp;
  short          token;
} FILE;
For more information, look in your compilers help.


Opening a file

Inside the program we open the file with the <stdio.h> function fopen()
 
fopen()
short for "file open". opens a file. 
function definition:    FILE *fopen(const char *filename, const char *mode)
Opens a file. returns 0 if unsuccesful.

fopen() returns a pointer to a FILE (which we can assign to our variable of type FILE-pointer above).
fopen()  takes two parameters, both strings (pointers to char). The first one is the name of the file and the second one is the way it should be opened, for reading ("r"), for writing ("w"), or for appending ("a").
Examples:
to open a file named "OLA.TXT" for reading we use
  FILE *f;
  f = fopen("OLA.TXT", "r");
to open a file named "output.asc" for writing we can use
  FILE *f;
  f = fopen("output.asc", "w");



 

Reading and Writing

Reading from file and wring to file is done in exactly the same way as reading and writing to screen, with the only modification that we will use fscanf() instead of scanf() for reading and fprintf() instead of printf() for writing. The first parameter of these function calls have to be our file handle (for example f)
 
fscanf()
short for "file scan fornatted". input from file 
function definition:    int fscanf(FILE *stream, const char *format, ....)
gets fromatted input from file

 
fprintf()
short for "file print formatted". Formatted output to file 
function definition:    int fprintf(FILE *stream, const char *format, ...)
outputs to a file. returns number of characters written, EOF if unsuccesful.

Note that we can only use the fscanf instructions for files that have previously been opened for input ("r") and fprintf is only to be used for files opened for output ("w"). Examples:
  fprintf(f, "%f", r);
  fscanf(f, "%d", opcao);
 

Read a variable with the keyboard
Read a variable from file
Write a variable to screen
Write a variable to file


Closing the file

When we are ready with the file, we must close it. This is especially the case for output files. If we forget to close the file before ending the program, probably not all the information will be written to the file (the "buffer" will not be emptied). To close the file we use fclose().
 
fclose()
short for "file close". Closes a file. 
function definition:    int fclose(FILE *stream)
closes a file. returns 0 if succesful.

for example:
  fclose(f);


Summary

File input and output consist of the following steps:


End-of-file testing

The following instruction can be useful
feof(filehandle): returns true if we are reading at the end of the file.
eof stands for end-of-file

Example:
  while (!eof(f))
  {
    fscanf("%s", s);
  }
which will read from the file until the end of the file is encountered.


Examples

code  screen  file TEST.TXT
after running the program
/* With File Output */
#include <stdio.h>

FILE *f;
char s[100];
int i;

void main()
{
  printf("Name of File:");
  scanf("%s", s);
  f = fopen(s, "w");
  for (i=1; i<=10; i++)
    fprintf(f, "%d Hello", i);
  fclose(f);
}

Name of File:
TEST.TXT
1 Hello
2 Hello
3 Hello
4 Hello
5 Hello
6 Hello
7 Hello
8 Hello
9 Hello
10 Hello

 
code  screen  file TEST.TXT before
running the program
/* With File Input */
 #include <stdio.h>

 FILE *f;
 char s[100];
 int i;

 void main()
 {
   printf("Name of File:");
   scanf("%s", s);
   f = fopen(s, "r");
   while (!feof(f))
    {
      fscanf(f, "%s", s);
      printf("%s\n", s);
    }
   fclose(f);
 }
 

Name of File:
TEST.TXT
1
Hello
2
Hello
3
Hello
4
Hello
5
Hello
6
Hello
7
Hello
8
Hello
9
Hello
10
Hello
1 Hello
2 Hello
3 Hello
4 Hello
5 Hello
6 Hello
7 Hello
8 Hello
9 Hello
10 Hello
The output is probably not what we would have liked. Maybe we should use the function fgets() instead to read strings. See below.

Other file functions

Other useful file functions are
 
fgets()
short for "file get string". Reads a string from file. 
function definition:    char *fgets(char s1, int n, FILE *stream)
reads a string from file until eol (end of line), eof (end of file) or maximum of n-1 characters are read

 
fgetc()
short for "file get char". Reads a character from file. 
function definition:    int fgetc(FILE *stream)
reads a single character from file. Returns value of character if successful.

 
fputs()
short for "file put string". Writes a string to file. 
function definition:    int fputs(const char s1, FILE *stream)
writes a string to file. Returns 0 if succesful.

 
fputc()
short for "file pu char". Writes a character to file. 
function definition:     int fputc(char *s1, FILE *stream)
Writes a single character to file. returns value of character if succesful.


Peter Stallinga. Universidade do Algarve, 17 December 2002