Header Ads Widget

File handling - Introduction, Operations, Reading, Writing, Closing

File handling

                                                         by sumit kumar



File handling - Introduction, Operations, Reading, Writing, closing

File handling. In this article, Everything will be told about File handling -
 
  • Introduction of File handling
  • File Operations
  • Opening a file
  • File Opening Modes
  •  Reading from a File
  •  Closing the File
  •  Writing to a file
  •  A File-copy Program
  •  String (line) I/O in Files
  •  Record I/O Files
File handling

What is File handling?

File handling means storing a kind of data permanent in a file rather than taking input aagain and again. The data you enter while running a program get lost when program terminates but when you will be using files creating and manipulating then the data you  entered or manipulated will be permanent saved to the computer disk

    Often it is not enough to just display the data on the screen. This is because if the data is large, only a limited amount of it can be stored in memory and only a limited amount of it can be displayed on the screen. It would be in appropriate to store this data in memory for one more reason. Memory is volatile and its contents would be lost once the program is terminated. So if we need the same data again it would haave to be either entered through the keyboard again or would  have to be regenerated programmatically.     


File Operations

There are different operations that can be carried out on a file. 
These are: 

  • Creation of a new file
  • Opening an existing file
  • Reading from a file
  • Writing to a file
  • Moving to a specific location in a file (Seeking)
  • Closing a file
Let us now write a program to read a file and display its contention the screen. We will first list the program and show what if does, and then dissect it line by line. Here we come with a sample program displaying just content of a file....

/*  Display contents of a file on screen.  */
# include  "stdio.h"
void main ()
{
     FILE  *fp;
     char  ch;
     fp  =  fopen   (  "Hello.txt", "r") ; 
     while  (1)
     { 
             ch = fgetc  ( fp )  ; 
             if   (  ch  ==  EOF  )  ; 
             break  ;
             printf  (  " c",  ch)  ;
     }
     fclose  ( fp )  ; 
}

On execution of this program it displays the contents of the file 'Hello.txt' on the screen. To use file handling function we need to #includestdio.h heder file into the program then only you can be able to use these. now we see them in detail about the functioning of these. 


Opening a file

Before we can read (or write) information from (to) a file on a disk we must open the file. to open the file we have called the function fopen( ). It would open  file "Hello.txt" in 'read' mode, which tells the C compiler that we would be reading the contents of the file.Note that "r" is a string and not aa character; hence the double quotes and not single quotes. In fact fopen( ) performs three important tasks when you open the file in "r" mode:

  • Firstly it searches on the disk the file to be opened and then
  • It loads the file from the disk into a place in memory called buffer. 
  • It sets up a character pointer that point to the first character of the buffer. 
To make sure opening a file you need ot declare a file pointer variable first then you can use fopen( ) to buffer a file in the program. Here we see....

FILE *fp ;

Now we see the syntax of opening a file in the program....

fp = fopen ( "Hello.txt", "r" ) ;

Now you can run a loop to read ech character from the file to the EOf (End of file).


File Opening Modes

In our first program on disk I/O we have opened the file in read ("r") mode. However, "r" is but one of the several modes in which we can open a file. Following is a list of all possible modes in which a file can be opened. the tasks performed by fopen( ) when a file is opened in each of these modes are also mentioned.

File Opening Modes


File Opening Modes



Reading from a File

Once the file has been opened for reding using fopen( ), as we have seen, the file's contents are brought into buffer (partly or wholly) and a pointer is set up that points to the first charcter in the buffer. This pointer is one of the elements of the structure to which fp is pointing.

To read the file's contents from memory there exists a function called fgetc ( ). This has been used in our program as,
ch = fgetc (fp);

fgetc ( ) reads the character from the current pointer position, advances the pointer position so that it now points to the next character, and returns the character that is read, which we collected in the variable ch. Note that once the file has been opened, we no longer refer to the file by its name, but through the file pointer fp


Closing the File

When we have finished reading from the file, we need to close it. This is done using the function fclose ( ) through the statement, 
fclose (fp);

Once we close the file we can no longer red from it using getc ( ) unless we reopen the file. Note that to close the file we don't use the file name but the file pointer fp. One closing the file the buffer associated with the file is removed from memory. 

When we close this file using fclose ( ) three operations would be performed:

  • The characters in the buffer would be written to the file on the disk.
  • At the end of file  a character with ASCLL value 26 would get written.
  • The buffer would be eliminated from memory. 

Writing to a File

The fputc ( ) function is similar to the putch ( ) function, in the sense that both output characters. However, putch ( ) function always writes to the VDU, whereas, fputc ( ) write to the file. Which file? the file signified by ft. The writing proces continue still all characters from the source file have been written to the target file, following which the while loop terminates. 

Here we see an example to write into a text file as follows...

#include <stdio.h>
void main( )
{
     FILE *fp :
     char s [80] ;
     fp = fopen ( "Hello.txt", "w" ;
     if  ( fp == NULL )
{
      puts ( "cannot open file" ) ;
      exit () ;
printf ( "\nEnter a few lines of text:\n") ;
while ( strlen (gets ( s ) ) > 0
{
      fputs ( s, fp ) ;
      fputs ( "\n", fp ) ;
}
fc;pse ( fp) ;
}

    
And here is a sample run of the program...
Enter a few line of text:

The first one in the file namely Hello, Say Hello ! 

and now when you want to read this file you just contents as input, follow the steps...

#include <stdio.h>
void main ( )
{
     FILE *fp;
     char s [80]
     fp = fopen ( "Hello.txt", "r" ) ;
     if  ( fp == NULL )
     {
          puts ( "Cannot open file" ) ; 
          exit ( ) ;
}
while ( fgets ( s, 79, fp ) ! = NULL )
printf ( "s", s ) ;
fclose ( fp ) ;
}


And here is the output...

The first one in the file namely Hello, Say Hello ! 


A File-copy Program

We have already used the function fgetc( ) which reads character from a file. Its counterpart is a function called fputc( ) which writes characters to a file. As a practical use of these character I/O functions we can copy the contents of one file into another, as demonstrated in the following program. This program takes the contents of a file and copies them into another file, character by character. 

#include <stdio.h>
void main ( )
{
      FILE *fs, *ft;
      char ch;
      fs = fopen ( "Hello.txt", "r");
      if ( fs == NULL)
      {
          puts ( "Cannot open source file");
          exit ( ); 
      }
      ft = fopen ( " demo.txt ", "w") ;
      if ( ft == NULL )
      {
          puts ( "cannot open target file" ) ;
          fclose ( fs ) ;
          exit ( ) ;
      }
       while (1)
      {
           ch = fgetc ( fs ) ;
           if ( ch == EOf )
           break;
           else
           fputc ( ch, ft ) ; 
      }
      fclose ( fs ) ; 
      fclose ( ft ) ;
}

I hope most of the stuff  in the program can be easily understood, since it has already been dealt with in the earlier section. what is new only the function fputc( ). let us see how it works. 


String (line) I/O in Files

For many purposes, character I/O is just what is needed. However, in some situations the usage of functions that read or write entire strings might turn out to be more efficient. Reading or writing strings of characters from and to files is as easy as reading and writing individual characters. Here is a program that writes strings to a file using the function fputs( ).

/* Receives strings from keyboard and writes them to file */
#include "stdio.h"
void main ( )
{
    FILE *fp;
    char s [80] ; 
    fp = fopen ( "Hello.txt", "w" ) ;
    if ( fp == NULL )
    {
         puts ( "Hello.txt", "w" ) ;
         exit ( ) ;
    }
    printf ( "\nEnter a few lines of text:\n" ) ;
    while (strlen (gets (s) >0 )
    {
         fputs (s, fp) ;
         fputs ( "\n", fp ) ;
    }
    fclose (fp) ;
}

And here is a sample run of the program....
A sentense I input here in a file

Record I/O in File

So far we have dealt with reading and writting only characters and strings. What if we want to read or write numbers from/to file? Further more, what if we desire to read/write a combination of characters, strings and numbers? For this first we would organize this dissimilar data together in a structure and then use fprintf ( ) and fscanf ( ) library functions to read/write data from/to file. Following program illustrates the use of structures for writing records of employees. 

/* writes records to a file using structure */
#include <stdio.h>
void main ( )
{
    FILE *fp;
    char another = 'y' ;
    struct emp
    {
         char name [40] ;
         int age ;
         float bs ;
    } ;
    struct emp e ;
    fp = fopen  ( "emp.dat", "w" ) ;
    if ( fp == NULL ) 
    {
        puts ( "cannot open file " ) ;
        exit ( ) ;
    }   
    while ( another == 'y' )
    {
        printf ( "\nenter name, age and basic salary: " ) ;
        scanf ( " %s %d %f\n ", e.name, e.age, e/bs ) ;
        printf ( " Add another record (Y/N) " ) ;     
        fflush ( stdin ) ;
        another = getche ( ) ;     
    }
    fclose ( fp ) ; 
}

And here is the output of the program...

Enter name, age and basic salary: vijay 34 7000.00
And another record (Y/N) Y
Enter name, age and basic salary: Dhananjay 2910000.00
And another record (Y/N) Y
Enter name, age nad basic salary: vaibhav 307500.00
Add another record (Y/N) N

Let us now write a program that reads the employee records created by the above program. Here is how it can be done...

/* Rad records from a file using structure */
#include <stdio.h>
void main ( )
[
      FILE *fp;
      struct emp
      {
           char name [40]
           int age ;
           float bs ;
      } ;
      struct emp e ; 
      fp = fopen ( "Emp.dat ", "r" ) ;
      if ( fp == NULL )
      {
      puts ( "cannot open file" ) ; 
      exit ( ) ; 
      }
      while ( fscanf ( fp, "%s %d %f", e.name, &e.age, &e.bs ) ! = EOF )
      printf ( "\n%s %d %f, e.name, e.age, e.bs ) ; 
      fclose ( fp ) ; 
}

And here is the output of the program...

vijay 34 7000.000000
Dhananjay 2910000.000000
vaibhav 30 7500.000000


 

Post a Comment

0 Comments