C - File Handling

Sometime it is necessary to store the output in a file for permanent storage instead of just displaying it. In C Language, this can be done with the help of file handling.

Using file handling we can do the following operations on a file.

  1. Create a new File
  2. Open an existing File
  3. Closing a file
  4. Read from a file
  5. Write in a file
  6. Searching in a file
  7. Updating in a file
  8. Deleting in a file
  9. Rename a file

C - File Handling Functions

There are many functions in C library which is use to open, read, write, search and close a file. A list of file functions is given below:

S.No. Function Syntax Description
fopen() filepointer=fopen("filename.ext","mode"); Open a file
fclose() fclose(filepointer); Close a file
fputc() fputc(char variable, filepointer); Write a character in a file.
fgetc() char ch=fgetc (filepointer); Read a single character from a file at a time.
fputs() fputs(string, filepointer); Write a string in a file.
fgets() fgets(string, numberofcharacters, filepointer); Read a string from a file.
fprintf() fprintf (filepointer,"%s %d", e.name, e.age); Write a record in a file.
fscanf() fscanf( fp, "%s %d", &e.name, &e.age); Read a record from a file.
fwrite() fwrite(&object, sizeof(object), 1, fp); Write a record in a file
fread() fread(&object, sizeof(object), 1, fp); Read a record from a file
fseek() fseek (fp, -recsize, SEEK_CUR); Search a record SEEK_END, SEEK_CUR, SEEK_SET
ftell() ftell(filepointer); To locate the current position
remove() remove("filename.txt"); To delete a file
rename() rename("Oldfilename","Newfilename"); Rename the file
rewind() rewind(filepointer); Sets the file pointer to the beginning of the file
feof() !feof(fp) or if (fp==NULL) To locate end of file.

C - File Handling Modes

File handling modes tells the compiler what action to be perfom on the file eg read, write, append etc. File handling modes are listed below:

S.No. Modes Description
r Opens an existing text file for reading purpose.
w Creates a new text file for writing purpose. If file already exists, then it open the file and overwrite it.
a Open a text file for writing in append mode, if it does not exist then a new file is created.
r+ Opens a text file for reading and writing both.
w+ Opens a text file for reading and writing both. It first truncate the file to zero length.
a+ Opens a text file for reading and writing both. It creates the file if it does not exist. The reading will start from the beginning but writing can only be appended.
If you are going to handle binary files then you can use below mentioned access modes:
S.No. Modes Description
rb Open a binary file in read mode
wb Open a binary file in write mode
ab Open a binary file in append mode
rb+ Open a binary file in read and write mode
wb+ Open a binary file in read and write mode
ab+ Open a binary file in read and write mode

Examples - File Handling

fputc() function: Use to write a single character into a file.

Example 1: WAP to input a character and write in a file.

#include<stdio.h>
#include<conio.h>
void main()
{
    char a;
    FILE *fp;
    clrscr();
    fp = fopen("file.txt","w");
    printf("Enter character: ");
    a = getchar();
    fputc(a,fp);
    fclose(fp);
}
The above program writes a character in a file, to check file content open 'my computer' check in a folder where Turbo C++ software installed generally it is in 'c:/turboc3/bin/file.txt'.
/* Use while loop to write a string in the file. '\r' is use for carriage return.*/
while(a!='\r')
{
    a = getche();
    fputc(a,f);
}

Example 2: WAP to Input a character and append in a file.

#include<stdio.h>
#include<conio.h>
void main()
{
    char a;
    FILE *fp;
    clrscr();
    fp = fopen("file.txt","a");
    printf("Enter character");
    a = getchar();
    fputc(a,fp);
    fclose(fp);
}
The above program appends a character in a file, to see the contents open the file via 'my computer' check in a folder where Turbo C++ software installed generally it is in 'c:/turboc3/bin'.

fgetc() function: Use to read a single character from a file.

Example 3.1: WAP to read a character from a file.

#include<stdio.h>
#include<conio.h>
void main()
{ 
    FILE *fp;
    char ch;
    clrscr();
    fp=fopen("file.txt","r");
    ch = fgetc(fp);
    printf("%c",ch);
    close(fp);
    getch();
}
Read only one character from 'file.txt' and display on console(output) screen

Example 3.2: WAP to read all characters from a file using loop.

#include<stdio.h>
#include<conio.h>
void main()
{ 
    FILE *fp;
    char ch;
    clrscr();
    fp=fopen("file.txt","r");
    while((ch=fgetc(fp))!=EOF)
    {
       printf("%c",ch);
    } 
    close(fp);
    getch();
}
Read all characters one by one using while loop from 'file.txt' and display on console(output) screen

fputs() function: Write a line of characters into a file.

Example 4.1: WAP to write a string in a file.

#include<stdio.h>
#include<conio.h>
void main()
{
    FILE *fp;
    clrscr();
    fp=fopen("file.txt","w");
    fputs("Hello fgets - fputs example",fp);
    fclose(fp);
}
No output on console screen. It will write message 'Hello fgets - fputs example' in a file.

Example 4.2: WAP to input a string and write in a file.

#include<stdio.h>
#include<conio.h>
void main()
{
    FILE *fp;
    char ch[80];
    clrscr();
    fp=fopen("file.txt","a");
    printf("Enter sentance:");
    gets(ch);
    fputs(ch, fp);
    fclose(fp);
}
No output on console screen. It will write message in a file which is entered by user.

fgets() function: Read a line of characters from the file.

Example 5: fgets function

#include<stdio.h>
#include<conio.h>
void main()
{
    FILE *fp;
    char text[80];
    clrscr();
    fp=fopen("file.txt","r");
    printf("%s",fgets(text,80,fp));
    fclose(fp);
    getch();
}
Hello fgets - fputs example

fprintf() function: Use to write set of characters into the file.

Example 6: fprintf() function

#include<stdio.h>
#include<conio.h>
void main()
{
    FILE *fp;
    clrscr();
    fp = fopen("file.txt", "w");
    fprintf(fp, "Hello fprintf example.");
    fclose(fp);
    getch();
}
No output on console screen. It will write message in a file.

fscanf() function: Use to read set of characters from the file. It reads a word from file and returns EOF at the end of file.

Example 7: fscanf() function

#include<stdio.h>
#include<conio.h>
void main()
{
    FILE *fp;
    char text[255];
    clrscr();
    fp = fopen("file.txt", "r");
    while(fscanf(fp, "%s", text)!=EOF)
    {
        printf("%s ", text);
    }
    fclose(fp);
    getch();
}
Hello fprintf example.

Example 8: Store employee information as entered by user. Store employee id, name, salary and display it.

#include<stdio.h>
#include<conio.h>
void main()  
{  
    FILE *fptr;  
    int id;  
    char name[30];
    float salary;
    clrscr();
    fptr = fopen("emp.txt", "w+");
    if (fptr == NULL)  
    {  
        printf("File does not exists \n");  
        return;  
    }  
    printf("Enter the id: ");  
    scanf("%d", &id);  
    fprintf(fptr, "Id= %d\n", id);  
    printf("Enter the name: ");  
    scanf("%s", name);  
    fprintf(fptr, "Name= %s\n", name);  
    printf("Enter the salary: ");  
    scanf("%f", &salary);  
    fprintf(fptr, "Salary= %.2f\n", salary);  
    fclose(fptr);  
    getch();  
}
Enter the id: 1
Enter the name: Dennis
Enter the salary: 150000

Now open file from current directory, you will see emp.txt file. It will have following information.
Id = 1
Name = Dennis
Salary = 150000

fseek() function: Use to set the file pointer to the specified offset. It is used to write data into file at desired location.

There are 3 constants used in the fseek() function: SEEK_SET, SEEK_CUR and SEEK_END.

Example 9: fseek() function

#include<stdio.h>
#include<conio.h>
void main()
{
    FILE *fp;
    clrscr();
    fp = fopen("file.txt","w+");
    fputs("This is fseek function", fp);
    fseek( fp, 7, SEEK_SET);
    fputs("replaced text", fp);
    fclose(fp);
    getch();
}

C rewind() function: Sets the file pointer at the beginning of the stream. It is useful if you have to use stream many times.

Example 10: rewind() function

#include<stdio.h>
#include<conio.h>
void main()
{  
    FILE *fp;  
    char c;  
    clrscr();  
    fp=fopen("file.txt","r");  
    while((c=fgetc(fp))!=EOF)
    {  
        printf("%c",c);  
    }  
    rewind(fp);//moves the file pointer at beginning of the file  
    while((c=fgetc(fp))!=EOF)
    {  
        printf("%c",c);  
    }  
    fclose(fp);    
    getch();    
}

As you can see, rewind() function moves the file pointer at beginning of the file that is why "this is simple text" is printed 2 times. If you don't call rewind() function, "this is simple text" will be printed only once.

ftell() function: returns the current file position of the specified stream. We can use ftell() function to get the total size of a file after moving file pointer at the end of file.

Example 11: ftell() function

#include<stdio.h>
#include<conio.h>
void main()
{
    FILE *fp;  
    int length;
    clrscr();
    fp = fopen("file.txt", "r");
    fseek(fp, 0, SEEK_END);
    length = ftell(fp);  
    fclose(fp);  
    printf("Size of file: %d bytes", length);  
    getch();  
}

fread(), fwrite() function: use to read and write a record in a data file

Example 12: fread(), fwrite() function

#include<stdio.h>
#include<conio.h>
struct student
{
    int rollno;
    char name[20];
};

void main()
{
    struct student st, st2;
    clrscr();
    printf("Enter Rollno and Name:");
    fflush(stdin);
    scanf("%d",&st.rollno);
    fflush(stdin);
    gets(st.name);

    FILE *fp;
    fp=fopen("record.dat", "a");
    fwrite(&st, sizeof(st), 1, fp);
    fclose(fp);

    fp=fopen("record.dat", "r");
    //fread(&st2, sizeof(st2), 1, fp); //read a single record
    while(fread(&st2, sizeof(st2), 1, fp))
    {
        printf("\nRollno = %d", st2.rollno);
        printf("\nName= %s", st2.name);
    }
    fclose(fp);
    getch();
}

rename() function: Use to rename a file. You can use variable or file name inside a rename function

Example 13: Input a filename and rename it with new name.

#include<stdio.h>
#include<conio.h>
void main()
{
    char oldname[50];
    char newname[50];
    clrscr();
    //rename("abc.dat","student.dat"); //using filename
    rename(oldname,newname); //using variable name
    getch();
}
Check folder file name is now changed

remove() function: Use to remove a file. You can use variable or file name to a rename function

Example 14: Input a filename and remove it.

#include<stdio.h>
#include<conio.h>
void main()
{
    char filename[50];
    clrscr();
    //remove("student.dat"); //using filename
    remove(filename); //using variable name
    getch();
}
Check folder file is now removed