File Handling In C

  • Before taking a deep dive into the concept of file handling , we will See what is the need of Files
  • Why there is a Need of Files?
  • As you know In C language , there are Input and Output Functions Which helps us to take Input from the User and print the Data on the screen.
  • Here because of Small amount of data , no problem arrives but In real life situation You have to deal with the large amount of data.
  • In such case , it becomes necessary to store the data so that User can access the data or User can make any changes according to his need.
  • This can be done by storing the data in a file as file can store large amount of data permanently.
  • So, then let's learn how to store , fetch a data and more...

File handling

  • As in case if you don't know what is file, it is just a collection of information stored in the secondary memory and whatever information is present in the secondary memory is called as Physical file.
  • We will see all the operations one by one individually.
  • Now we will start with file opening operation

File Opening Operation

  • No operation can be perform on the file when it is on the disk.
  • For performing any operation on a file we have to bring a copy of a file from a disk into the memory.
  • Only after bringing copy of the file in the memory, we can perform any operation on it.
  • Bringing the copy of a file into the memory from a disk is known as Opening a file.
  • For opening a file C language Provide a in-built function fopen() which takes two parameters.
  • First parameters is name of file and second is the mode of file.
  • This function is defined in stdio.h file.
  • Syntax: fopen() Function
    fopen("file_name","opening_mode");
    
  • fopen() function returns a file pointer if file gets open successfully otherwise returns null
  • There are various modes of opening a file , see the below table of various mode of opening a file.
Mode Description
r Open a text file for only reading purpose, only if file is present otherwise file pointer return Null

w Open a file for writing , if file is not present a new blank file will be created with specified name and open it for writing , if any how file is unable to open the file Pointer Returns Null.
If a file already exists then content of that file is fully erased and fresh new blank file is open for writing.

a Open a file for appending to existing text file. In this mode data is added at the end of the file without destroying the content of a file.
if file is unable to open then file pointer returns Null.

r+ Open a text file for reading as well as for writing

w+ Open a existing text file, if file does not exists it creates a file for writing and reading.

a+ Open a existing text file for reading and appending.Appends or creates a file for reading and writing.if file is not present a new blank file will be created with specified name.

rb Open a binary file for reading.

wb Open a binary file for writing.

ab Open a binary file for appending.
rb+ opens a binary file in both reading and writing mode, and the original content is overwritten if the file exists.

wb+ opens a binary file in both reading and writing mode and works similar to the w+ mode for binary files. The file content is deleted first and then new content is added.

ab+ opens a binary file in both reading and appending mode and appends data at the end of the file without overwriting the existing content.

fcolse() Function

  • A file needs to be closed after a read or write operation to release the memory allocated by the program.
  • In C, a file is closed using the fclose() function. This returns 0 on success and EOF in the case of a failure.
  • An EOF is defined in the library called stdio.h. EOF is a constant defined as a negative integer value which denotes that the end of the file has reached.

Syntax: fclose() Function
fclose(file_pointer);

File Pointer

  • What is File Pointer?
  • File pointer is a pointer which is used to handle and keep track on the files being accessed.
  • A new data type called “FILE” is used to declare file pointer.
  • This data type is defined in stdio.h file. File pointer is declared as FILE *fp. Where, ‘fp’ is a file pointer.
  • Syntax: Declaring a File Pointer
    FILE *pointer_name; 
    

Now we will work on text file 'test.txt' , take a look in the content of the text file.
C  is a general-purpose, procedural computer programming 
language supporting structured programming,
 lexical variable scope, and recursion, 
while a static type system
 prevents unintended operations. By design,
 C provides constructs that map 
efficiently to typical machine instructions, and has found lasting use 
in applications previously coded in assembly language. Such applications include 
operating systems, as well as various application software 
for computers ranging from supercomputers to embedded systems.

We will just Open a file 'test.txt' and we will check whether the file is opening correctly or not.

#include<stdio.h>

int main()
{
    FILE *fp;

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

    if(fp==NULL)
    {
        printf("Unable to open a file");
    }
    else
        printf("File is open Successfully.");

 //closing the file.
    fclose(fp);
}

Output:
File is open Successfully

Let's learn how to print the data of file on the screen before that Understand what is EOF and feof?

  • A file contains larger amount of data , and we can't detect end of file.
  • In Text files, a special character EOF denotes the end of file.
  • EOF is a predefined MACRO with the value of -1 that means EOF is not a character.
  • So EOF is returned through the function which is going to read content from the file.
  • In C, getc() function is use to read character from the file and returns EOF when end of file is reached.
  • Function getc() also returns EOF when it fails.
  • So, only comparing the value returned by getc() with EOF is not sufficient to check for actual end of file.
  • To solve this problem, C provides feof() which returns non-zero value only if end of file has reached, otherwise it returns 0.

Program of Printing a content of a file : We are working on "test.txt file you can see the content of that file we have shown it above."
#include<stdio.h>

void main()
{
    FILE *fp;
    char ch;


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

    if(fp==NULL) //Exp1
    {   
        printf("File Opening Errors");
        exit(1);
    } 
    else //Exp2
    {    
        while(feof(fp) == 0)
        {
            ch = getc(fp);
            putch(ch);
        }
    }
    fclose(fp);
}

  • Exp1: As you know fopen() function returns a file pointer , So we are checking that pointer whether it is Null or Not. If pointer is Null then we are printing error message and taking exit from the program
  • Exp2: If File Pointer is Not Null then we are doing the process of printing the content of file "test.txt".We are reading characters of file by getc() function and printing that character by putch() until the end of file does not occurs.
Output:
C  is a general-purpose, procedural computer programming 
language supporting structured programming,
 lexical variable scope, and recursion, 
while a static type system
 prevents unintended operations. By design,
 C provides constructs that map 
efficiently to typical machine instructions, and has found lasting use 
in applications previously coded in assembly language. Such applications include 
operating systems, as well as various application software 
for computers ranging from supercomputers to embedded systems.






  • This is how we can open and close a file.
  • Now we have learn opening a file in r mode, further we will see all other modes.