Image

C Language - File Handling - File Handling

File Handling

Wherever there is a need to handle large volumes of data, it is advantageous to store data on the disks and read whenever necessary. This method employs the concept of files to store data. A file is a place on disk where a group of related data is stored.

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

    1. 1. naming a file
      2. opening a file
      3. reading data from a file
      4. writing data to a file
      5. closing a file
  • There are two distinct ways to perform file operations in C.

    1. Low level I/O Operation (It uses operating system calls)
    2. High level I/O Operation (It uses functions in C's Standard I/O library)
    Table : List of High Level I/O Functions


    Function Name and their operation
    fopen()  Creates a new file for use or opens an existing file for use.
    fclose() Closes a 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.
    Opening a file

    When we open a file, we must specify what we want to do with the file. Following is the general format for declaring and opening a file:

    File *fp;
    fp = fopen ( "filename", "mode");

    The first statement declares the variable fp as a "pointer to the 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 the system and the program. The second statement also specifies the purpose of opening this file. The mode does this job.

    Mode can be one of the following:

    r :- Opens the file for reading only.
    w :-Opens the file for writing only.
    a :-Opens the file for appending (or adding) data to it.
    Both the filename and mode are specified as string. They should be enclosed in double quotation marks.

    Depending on the mode specified, one of the following actions may be performed:

    1. When the mode is 'writing', a file with the specified name is created, if the file does not exist. The contents are deleted, if the file already exists.

    2. When the purpose is 'appending', the file is opened with the current contents safe. A file with the specified name is created if the file does not exist.

    3. If the purpose is 'reading', and if it exists, then the file is opened with the current contents safe, otherwise an error occurs.

    Other additional modes of operation are: r+ The existing file is opened from the beginning for both reading and writing.
    w+ Same as w except both for reading and writing.
    a+ Same as a except both for reading and writing.
    Whenever a file is opened using fopen function, a file pointer is returned. If the file cannot be opened for some reason, then the function returns a null pointer.

    This facility can be used to test whether a file has been opened or not.

    if (fp == NULL)
    printf ("File could not be opened.\n");

    Closing a File

    Once all the operations on a file have been completed, the file is closed. This is done to clear the buffers and flush all the information associated with the file. It also prevents any accidental misuse of the file. In case there is a limit to the number of files that can be kept open simultaneously, closing of unwanted files might help open the required files. When there is a need to use a file in a different mode, the file has to be first closed and then reopened in a different mode.

    The I/O library supports a function for this of the following form
    fclose (file_pointer);

    Input/Output Operations on Files getc & putc Functions These are analogous to getchar and putchar functions and can handle only one character at a time.
    putc can be used to write a character in a file opened in write mode. A statement like putc (ch, fp1); writes the character contained in the character variable ch to the file associated with file pointer fp1.
    Similarly, getc is used to read a 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 is fp2. getw & putw Functions
    The getw and putw are integer-oriented functions. They are similar to the getc and putc functions and are used to read and write integer values on UNIX systems.

    The general forms of getw and putw are:
    putw (integer, fp); & getw (fp); fprintf & fscanf Function

    The general forms of getw and putw are: putw (integer, fp); & getw (fp); fprintf & fscanf Function

    Functions for Random Access to Files

    To randomly access only a particular part of a file, the following functions are provided in C.
    a. ftell
    b. rewind
    c. fseek ftell( ) Function
    ftell takes a file pointer and returns a number of type long that corresponds to the current position. This function is useful in saving the current position of a file, which can be used later in the program.

    n = ftell (fp);

    n would give the relative offset (in bytes) of the current position. This means that n bytes have already been read (or written). rewind( ) Function rewind takes a file pointer and resets the position to the start of the file.

    For example, the statements rewind (fp);
    n = ftell (fp);

    would assign 0 to n because the file position has been set to the start of the file by rewind.
    This function helps us in reading a file more than once, without having to close and open the file. Note: The first byte in the file is numbered as 0, second as 1, and so on. Whenever a file is opened for reading or writing, a rewind is done implicitly.
    fseek( ) Function fseek function is used to move the file position to a desired location within the file.

    Its syntax is fseek (fileptr, offset, position)

    z fileptr is a pointer to the file concerned. z offset is a number or variable of type long. It specifies the number of positions (bytes) to be moved from the location specified by position.

    WAP to write file using fputc
    #include<stdio.h>
    #include<conio.h>
    void main()
    {
      FILE *fptr;
      char ch;
      fptr=fopen("file11","w");
      if(fptr==NULL)
      {
       printf;("File does not exist");
       exit(1);
       }
       printf("\nEnter text ");
       while((ch=getchar())!=EOF)
    	fputc(ch,fptr);
       fclose(fptr);
      getch();
    }
    WAP for copying file
    #include<stdio.h>
    #include<conio.h>
    main()
    {
      FILE *fptr;
      char ch;
      fptr=fopen("file11","w");
      if(fptr==NULL)
      {
       printf;("File does not exist");
       exit(1);
       }
       printf("\nEnter text ");
       while((ch=getchar())!=EOF)
    	fputc(ch,fptr);
       fclose(fptr);
      getch();
    }