Make your own free website on Tripod.com

Lesson 10: File Management In C.

Prev || Home || Next

Bar_line.gif (11170 bytes)

    Until now, we have been using the functions such as scanf() and printf() to read and write data. These console oriented I/O functions which always use the terminal as the target place. They pose two major problems-    

    1) It becomes difficult and time consuming to handle large volumes of data through terminals.

    2) The entire data is lost when either the program is terminated or the computer is turned off.

        It is therefore necessary to use concept of files where data can be stored on the disk and read whenever necessary.

  C supports a number of functions that have the ability to perform basic file operations which include-

    1) Naming file.

    2) Opening file.

    3) Reading data from a file.

    4) Writing data to a file.

    5) Closing a file.

        We shall discuss the standard file handling functions that are available in C library.

Function Name Operation
foopen() Creates a new file for use or opens existing file for use
fclose() Closes the file which has been opened for use.
getc() Reads a character from a file.
putc() Writes a character to a file.
fprintf() Writes a set of data values to a file.
fscanf() Reads a set of data values from a file.
getw() Reads an integer from a file.
putw() Writes an integer to a file.
fseek() Set the position to desired point in the file.
ftell() Gives the current position in the file(in terms of bytes from the   start).
rewind() Sets the position to the begining of file.

     Defining and Opening a File:

          If we want to store data in a file in the secondary memory, following things are to be specified.

    1) File name.    2) Data structure.    3) Purpose.

        File name may contain a primary name and optional period with extension. Data structure of  file is defined as FILE in the library of standard I/O function definition. Therefore, all files will be declared as type FILE before they are usef. File is a defined data type. Following is the general format for declaring and opening a file:   

    File *fp;

    fp=fopen("file name","mode");

            The first statement declares the variable fp as a "pointer to data type FILE". The second statement opens the file named filename and assigns an identifier to the FILE type pointer fp. This pointer which contains all the information about the file is subsequently used as a communication link between system and program.

    The second statement also specifies the purpose of opening the file. This is done by mode which can be one of the following:    

    1) r- opens the file for reading only.    

    2) w- opens a file foe writing only.    

    3) a- opens the file for appending(adding) data to it).

    Consider the following statement

    file *p1,*p2;

    p1=fopen("data","r");

    p2=fopen("result","w");

            The file data is openend for reading and result for writing. In case, the result file already exists, its contents are deleted and the file is opened as a new file. In case, data files does notexists, an error will occur will accur. We can open and use .

   Closing a file:

                        After use, file should be closed for many reasons. It takes the following form.

                            fclose(file_pointer);

                            This would  close the file associated with the file_pointer. Look at the following segment of a program:

    ---------------

    ---------------

    FILE *p1,p2;

    p1=fopen("INPUT","w");

    p2=fopen("OUTPUT","r");

    ----------------

    ----------------

    fclose(p1);

    fclosw(p2);

    ----------------

            This program opens two files & closes them after all operations on them are complete. Once a file is closed, its file pointer can be used for another file.

    Input/Output Operations on Files:

            Once a file is opened, reading out of or writing to it is accomplished using the standard I/O fubctions. The getc() & putc() functions are standard I/O functions.

                The simpleset file I/O functions are getc() and putc(). These are analogous to getchar() & putchar() functions & handle one character at a time. Assume that a file is opened with mode w & file pointer fp1. Then the statement putc(c,pf1); writes the character contained in variable c to the file associated with FILE pointer fp1. Similarly getc() is used to read character from a file that has been opened in read mode. The statement c=getc(fp2); would read a character from the file whose file pointer has been reached.

    Program:- Writing to and reading from a file.

    #include<stdio.h>

    main()

    {

        FILE *f1;

        char c;

        printf("Data Input\n\n");

        f1=fopen("INPUT","w");

        while((c=getchar())=EOF)

        {

            putc(c,f1);

            fclose(f1);

            printf("\nData Output\n\n");

          }

            f1=fopen("INPUT","r");

            while((c=getc(f1))!=EOF)

            {

                printf("%c",c);

                fclose(f1);

            }

    }

   The getw() & putw() functions:

                  The getw() & putw() are integer-oriented functions. They are similar to getc() & putc() functions and are used to read and to write integer valuyes. The general form is:

   putw(integer,fp);

   getw(fp);

   Program:

    #include<stdio.h>

   main()

   {

      FILE *f`1,*f2,*f3;

      int number,i;

      printf("Contents of Data File\n\n");

      f1=fopen("DATA","e");

        for(i=1;i<=30;i++)

        {

            scanf("%d",&numbers);

            if(number==-1)

            break;

            putw(number,f1);

        }

        fclose(f1);

        f1=fopen("DATA","r");

        f2=fopen("ODD","w");

        f3=fopen("EVEN","w");

        while((number=getw(f1))!=EOF)

        {

            if(numbetr%2==0)

            putw(number,f3);

            else

            putw(number,f2);

       }

        fclose(f1);

        fclose(f2);

        fclose(f3);

        f2=fopen("ODD","r");

        f3=fopen("EVEN","r");

        printf("\nContents of ODD file\n");

        while((number=getw(f2))!=EOF)

        printf("%4d",number);

        printf("\nContent of EVEN number\n");

        while((numbere=getw(f3))!=EOF)

        printf("%4d",number);

        fclose(f2);

        fclose(f3);

    }

    The fprintf() & fscanf() Functions:

            So far we have seen functions which can handle only one character or integer at a time. There are two functions fprintf() and fscanf() which are indentical to printf() and scanf() functions except of course they work on files. The general form of fprintf is

        fprintf(fp,"control string,list);

    where fp is a file pointer associated with a file that has been opened for writing. The control string contains output specifications for the items in the lisr. The list may include variables, constants and strings Ex.

    fprintf(f1,"%s%d%f",name,age,7.5);

    Here name is an array variable to type char and age is an integer variable. The general form of fscanf() is

    fscanf(fp,"control string",list);

    ex. fscanf(f2,"%s%d",&item,&quantity)

    Like scanf, fscanf also returns the numbers of items that are successfully read. When the end of file is reached, ite returns the value of EOF.

    Program:-

    main()

    {

        FILE *f1;

        char item[20];

        int i,no,qty;

        float price,value;

        f1=fopen("INPUT","w");

        for(i=1;i<=3;i++)

        {

            printf("Name,number,quantity and price:- ");

            scanf("%s%d%d%f",&item,&no,&qty,&price);

            fprintf("%s%d%d%f",item,no,qty,price);

        }

        fclose(f1);

    }

    fseek(), ftell() and rewind() Functions:

       Once a file has been opened, we may want to access the specific part of the file. This is done by positioning the file pointer at the desired position in the file. This can be achieved through the functions rewind() and fseek().

    rewind():- rewind() positions the file pointer right at the begining of the file. The general statement is

                    rewind(fp);

    fseek():- fseek() function is versatile since it can place the file pointer virtually anywhere in the file. Its general format is fseek(file pointer,+/-no of bytes,anchor);

                On calling fseek it positions the file pointer ahead(if+) or behind(if-) the location specified by anchor. The anchor can be

                1) seek_set - Begining of the file.

                2) seek_end - End of file.

                3) seek-cur - Current Position.

    ftell():- ftell() is the function which gives you the current position of the file pointer in the file.

                Ex. p=ftell(fp);

                will return the current position of the file pointer in terms of byte which will be stored in integer.

Binary Data Files:

            Some applications involve the use of data files to store blocks of data. Each block will generally represent complex data structure. For ex. a  data file may contain multiple structures having the same composition or it may contain multile arrays of the same type and size. For such applications, it is desirable to read the entire block from the data file rather than reading or writing individual component within each block separately. The library functions fread() and fwrite() are used in such a situation. Each of these functions require four arguments pointer to the data block, the size of the data block, the number of data blocks being transferred the string pointer variable p.

    For Ex. fwrite(&rec,sixeof(struct record),5,fp);

    Using the array of structure you can input the 5 records from the terminal using for loop below.    

    struct record

    {

        char name[20];

        int age;

        float salary;

    }

    struct record rec[5];

    for(i=0;i<5;i++)

    {

        scanf("%s%d%f",rec[i].name,rec[i].age,rec[i].salary);

    }

        Then open the file to which you want to transfer the records using the fopen function.

        fp=fopen("DATA","wb");

        Now all the inputed records will be transferred to file DATA by following statements

        fwrite(&rec,sizeof(struct record),5,fp);

      In the same way you can use fread() function also to read the records from a file.

Bar_line.gif (11170 bytes)

Prev || Home || Next