File Handling in C

This article contains everything you need to know regarding file handling and working with files till class 12.
 

Concept of the data file

The input and output operations that we have performed so far were done through screen and keyboard only. After the termination of the program, all the entered data is lost because primary memory is volatile. If the data is to be used later, then it becomes necessary to keep it in the permanent storage device. A file is a collection of related data placed on the disk. A data file is a collection of related data records placed and stored on the disk that can be modified (processed) as per requirement. C language supports the concept of files through which data can be stored on the disk or secondary storage devices. The stored data can be read and manipulated whenever required. A file represents a sequence of bytes on the disk where a group of related data is stored. The file is created for the permanent storage of data. It is a readymade structure.
 

Files supported by C language

  1. Text files: A text file is a sequence of characters and words they form which is encoded into computer-readable formats. A text file is also known as an ASCII file and can be read by any word processing package. These files cannot store the sound, video, and graphics. In-text files, everything is stored in terms of text.
  2. Binary files: A binary file contains data that is written in the same format used to store internally in the main memory. For example, the integer value 1245 will be stored in 2 bytes depending on the machine while it will require 5 bytes in a text file. Thus Binary file represents the contents in contiguous bytes. It can access sound, video, and graphics. A binary file is made up of machine-readable symbols that represent 1s and 0s.
 

File Pointer

The file pointer is a special type of pointer variable used to declare files in C programming. To access any file, we need to declare a pointer FILE structure and then associate it with a particular file. This pointer is referred as a file pointer and it is declared as follows:
 
FILE *fp;
 

Methods of file accessing

In terms of file access in C programming, it supports two types of files. They are:
  1. Sequential access files: Sequential access of files allows reading the data from the file in a serial manner which is means that data can only be read in sequence. Data accessing is slower and time-consuming because it has to read all the data unnecessarily.
  2. Random access file: This is a file type that allows reading data from any location in the file directly or randomly. Therefore data accessing will be faster in comparison to a sequential file. C defines a set of functions to manipulate the position of the file pointer.
 

Opening a data file in different modes

A file must be opened before any input. output operations performed on that file. The process of establishing a connection between the program and file is called opening the file.
 
Syntax: FILE *fopen(const char *filename, const char*mode);
 
“fopen()” function takes two strings as arguments, the first one is the name of the file to be opened and the second one is the mode that decides which operations (read, write, append) are to be performed on the file.
 
 
FILE *fp1,fp2;
fp1 = fopen(“myfile.txt”, “w”);
fp2 = fopen(“yourfile.dat”,”r”);
 
 

Possible values of modes

  1. “w” (write): If the file doesn’t exist then this mode creates a new file for writing, and if the file already exists then the previous data is erased, and newly entered is written to the file.
  2. “a” (append): If the file doesn’t exist then this mode creates a new file, and if the file already exists then the new data is entered is appended at the end of existing data. In this mode, the data existing in the file is not erased as in “w” mode.
  3. “r” (read): This mode is used for opening an existing file for reading purposes only. The file to be opened must exist and the previous data of the file is not erased.
  4. “w+” (write + read): This mode is the same as “w” mode but in this mode, we can also read and modify the data. If the file doesn’t exist then a new file is created and if the file exists then previous data is erased.
  5. “r+” (read + write): This mode is the same as “r” mode but in this mode, we can also write and modify existing data. The file to be opened must exist and the previous data of the file is not erased. Since we can add new data and modify existing data so this mode is also called update mode.
  6. “a+” (append + read): This mode is the same as the “a” mode but in this mode, we can also read the data stored in the file. If the file doesn’t exist, a new file is created and if the file already exists then new data is appended at the end of existing data. We cannot modify existing data in this mode.
  7. “a+t”: This mode is used to create or open a text file in reading mode.
  8. “rb”: This mode is used to open a binary file in read-only mode.
  9. “wb”: This mode is used to open a binary file in write-only mode.
  10. “r+b”: This mode is used to open a binary file in reading and write mode.
  11. “w+b”: This mode is used to open a binary file in write and read mode.
  12. “a+b”: This mode is used to open a binary file for append mode.
 

Closing a file

The file that was opened using fopen() function must be closed when no more operations are to be performed on it.
 
Syntax: int fclose(FILE *fp);
 

File functions

File functions are predefined collections of commands used for specific purposes for the data file. The following are the common function used for handling the data files in C language.
  1. fseek(): The function fseek() is used to set the file position in the data file.
    Syntax:int fseek(FILE *fp, long offset, int pos);

     

  2. ftell(): This function returns the current position of the file position pointer. The value is counted from the beginning of the file.
    Syntax: long ftell(FILE *fp);
  3. rewind(): This function is used to move the file position pointer to the beginning of the file. This function is useful when we open a file for updates.
    Syntax: rewind(FILE *fp);
  4. fopen(): This function is used to open a data file in a specified mode that allows for entering, modifying, or adding data in the data file.
    Syntax: File pointer = fopen("File name with extension", "file opening mode");
  5. fputc(): This function writes a character to the specified file at the current file position and then increments the file pointer position.
    Syntax: int fputc(int c, FILE *fptr);

     

  6. fgetc(): This function is used for input operation in data files. The operations of getc() to accept the text character.
    Syntax: int fgetc(FILE *fptr);
  7. fputs(): This function writes that null-terminated string pointed to by str to a file that means outputs the line of string data.
    Syntax: int fputs(const char *str, FILE *fptr);
  8. fgets(): This function is used to read characters from a file and these characters are stored in the string pointed by str which means accepts the line of string data.
    Syntax: char *fgets(char *str, int n, FILE *fptr);
  9. fprintf(): This function is the same as the printf() function but it writes formatted data into the file instead of the standard output.
    Syntax: fprintf(FILE *fptr, const char *format[arguments]);
  10. fscanf(): This function is similar to the scanf() function but it reads data from files instead of the standard input device, so it has one more parameter which is a pointer of FILE type and it points to the file from which data will be read.
    Syntax: fscanf(FILE *fptr, const char *format[address]);
  11. fwrite(): This function is used for writing an entire block to a given file.
    Syntax: size_fwrite(const void *ptr, size_t size, size_tn, FILE *fptr);
  12. remove(): This function is used to delete the file whose syntax is as follows:
    Syntax: remove(filename);
  13. rename(): This function is used to rename an old file name into a new file name.
    Syntax: rename(old_file_name, new_file_name);
 

Reading data from the data file (r)

Reading data means locating and accessing data contents from the data file. Opening a file for reading requires that the file already exists. If the data file does not exist, the file pointer will be set to NULL and can be checked by the program. For reading data, the mode “r” is used. When “r” is used, the file is opened for reading mode and we can read and store data to a particular file or secondary device, or data can be accessed from the file and assigned to the suitable variable items.
 
    // program to display the contensts of a file on screen using C language
    #include <stdio.h>
    void main()
    {
        FILE *fopen(), *fp;
        int c;
        fp = fopen("prog.c","r");
        c=getc(fp);
        while (c!=EOF)
        {
            putchar(c);
            c=getc(fp);
        }
        fclose(fp);
    }
 

Writing data to the data file (w)

The process of sending the data to be stored in the data file or secondary storage device is known as writing data. When a file is opened for writing, it will be created if it does not already exist and it will be reset if it does, resulting in the deletion of any data already there.
 
 
#include <stdio.h>
int main()
{
    FILE *fp;
    file = fopen("file.txt","w");
    fprintf(fp,"%s","This is just an example:)");
    fclose(fp);
    return 0;
}
 

Appending data to the data file (a)

Appending is the process of adding or inserting more data into an already existing data file. When a file is opened for appending, it will be created if it does not already exist and it will be initially empty. If it does exist, the data input point will be positioned at the end of the present data so that any data will be added to any data that already exists in the file.
 
    #include <stdio.h>
    int main()
    {
        FILE *fp;
        file = fopen("file.txt","a");
        fprintf(fp,"%s","This is just an example:)");
        fclose(fp);
        return 0;
    }
 
 
 
File Handling in C Programming (Everything You Need To Know Till Class 12)

Similar Posts

Leave a Reply

Your email address will not be published. Required fields are marked *