Introduction to Files

When some amount of data is to be stored in a file, the file is organized in the form of a table with rows and columns.

Assume that in an organization, employee details have to be maintained. There are five employees, and details like the employee's name, roll no. and salary have to be stored. The employee file would look like this

Name Roll no Salary
James E01 2000
Jerry E02 4100
Sheryl E03 3000
Meera E04 2500
Veena E05 5000

The details of one particular employee, say for example, Jerry, would form a row, in other words, a record.

Jerry E02 4100

The names of all the employees put together, or the designations of all the employees would form a column, in other words, a field.

Name
James
Jerry
Sheryl
Meera
Veena

This method of file organization i.e., as tables with fields and records, is discussed later in the session. Now let us look at the way in which files are handled in C.      

File Handling

File handling in C is very simple, as it essentially treats a file as just a stream of characters and accordingly allows input and output in streams of characters. Functions are available for single character as well as multiple character input/output from/to files. This simplicity has the advantage that it provides a programmer the flexibility to write to the file as and when he/she wishes to.


Let us take the example of a file exam.dat. This file has to be read sequentially till the end of file is reached i.e., there are no more characters to be read. The steps involved in it would be  

  • Open the file
  • Read the file sequentially and display it on the screen
  • Close the file.

Opening a File (fopen)

A file can be opened using the function fopen (). The statements that are used for opening a file in C are   

#include
void main
{
   FILE *fileptr; /* FILE is a datatype defined in the header file stdio.h, to which fileptr is declared as a pointer */
   fileptr = fopen ("exam. dat", "r");
}

The library function

fopen (filename, mode)

opens the specified file exam.dat in the read-only mode. Mode specifies the way in which a file is to be opened (here, it is read- only), which means that the file can only be read from and not written into. The function returns a FILE type pointer, which is assigned to fileptr. There are many ways, or modes, in which a file can be opened –

  • "r" read-only mode. Specifies that the file can only be read from and not written into.
  • "w"-the file is opened in the write-only mode. This means that the file can only be written into. Nothing can be read from it. If the file already contains data in it, the data is erased, and if no file in the specified name exists, it is created and opened in the write-only mode.
  • "a"-append mode. The file is opened in the write-only mode, the only difference being that the data that is being written onto the file gets appended at the end of the file (if the file contains data, it is not truncated).
  • "r+"-the file is opened in the read + write mode. The file must first be read from, and then it can be written onto.
  • "w+"- the file is opened in the write + read mode. The file can first be written onto, and then read from
  • "a+" - allows existing data to be read, and then new data to be added at the end of the

Character I/O from Files

Two functions facilitate character input and output from files –

fgetc (file pointer)

fputc (character, file pointer)

These are just extensions of the character I/O functions we are already familiar with. The only additional parameter is the PILE type pointer that specifies the file from which data is to be read from or written into. fgetc() reads a character from the file, positions the pointer at the next character in the file, and returns the character just read. fputc() writes the given character onto the file at the current position of the pointer. The following program reads the file exam.dat (assuming that the file exists) character by character, prints it on the screen –

Example 7.1

#include
void main()
{
   char C
   FILE *fileptr;  
   fileptr = fopen ("exam.dat", "r");     /* now that the file is opened in the read-only mode, it is ready to be read from */
   c=fgetc (fileptr); 
   while (c != EOF)   /* EOF is a constant defined in the header stdio.h, it indicates end of file */
   {
      printf("%c", c);
      c=fgetc (fileptr); 
   }
}

The NULL return value

Whenever fopen() is unsuccessful (say, the file is to be opened in the read mode and the file does not exist) it returns a NULL type pointer. This can be used to check for errors when the file is being opened.

Till now we looked at read operations performed on one file and the result displayed on the Screen. Now let us look at a program that opens two files parallely, one in the read mode and the other in the write mode. It reads the first file and writes data onto the other.

Example 7.2

#include
void main()
{
   char c;
   FILE *fileptr1, *fileptr2; 

    /* assume that two files, exam1.dat and exam2.dat exist already, one to be read from and the other to be written onto */ 
    /* file is opened in the read-only mode */ 
    fileptr1 = fopen ("exam1.dat", "r");

    /* file is opened in the write-only mode */ 
    fileptr2 = fopen( "exam2.dat", "w");
    C=fgetc (fileptr1);
    while(c!=EOF)       /* EOF is a constant defined in the header stdio.h, it indicates end of file */
    {
       fputc (c, fileptr2);
       c=fgetc (fileptr1);
    }
}

Closing a File (fclose)

It is always good programming practice to close a file after it is used. The function used to close a file is

fclose (file pointer);

The following piece of code illustrates the usage of the function fclose –

#include 
void main()
{
   char c; 
   FILE *fileptr; 
   fileptr = fopen ("exam.dat", "r"); 
   …
   …     /* the file is read /
   …
   fclose (fileptr); 
}

The stdin, stdout and stderr pointers

These are nothing but FILE type pointers defined in the header stdio.h. Just keep in mind that the standard input device (keyboard) and standard output and error device (VDU) - which are referred to as stdin, stdout and stderr respectively - are just treated as files in C. File related operations can be performed on these files just as on any other ordinary file. For example, the statement

fputc (c, stdout):

displays the character c on the screen, and the statement

c = fgetc (stdin);

accepts a character as input from the keyboard and assigns it to c, whereas,

fputc (c, stderr);

also displays the character on the screen. Though the output and error devices are the same. there are subtle differences between the two.