Dremendo Tag Line

Text File Handling in C

File Handling in C

In this lesson, we will learn how to handle text file in C.

What is Text File Handling

Text File Handling is a process in which we create a text file and store data permanently on a hard disk so that it can be retrieved from the memory later for use in a program.

In a text file, whatever data we store is treated as text. Even if we store numbers, it is treated as text.

video-poster

Operation on Text File

There are different types of operations that we can perform on a text file, they are:

  • Create a new file.
  • Open an existing file.
  • Write to a file.
  • Read from a file.
  • Copy a file from one location to another.
  • Rename a file.
  • Delete a file.

Text File Opening Modes

Below we have discussed the different types of text file opening modes use to open a file.

Mode Description
r Open file for reading only.
w Open file for writing only. It creates the file if it does not exist. If the file exists, then it erases all the contents of the file.
a Open file for appending text. Text is added to the end of the file. It creates the file if it does not exist.
r+ Open file for both reading and writing.
w+ Open file for both reading and writing. It creates the file if it does not exist. If the file exists, then it erases all the contents of the file.
a+ Open file for reading and appending text. Text is added to the end of the file. It creates the file if it does not exist.

Create a new file

The program given below demonstrates how we can create a new text file in memory.

Example

#include <stdio.h>
#include <conio.h>

int main()
{
    FILE *fp;

    fp = fopen("e:/data.txt", "w");
    if(fp == NULL)
    {
        printf("Cannot open file");
        exit(0) ;
    }

    fclose(fp);
    return 0;
}

In the above program, FILE is an inbuilt data structure used to access files. The *fp is a pointer variable of FILE data type which is declared to store the memory address of the file we want to access.

The fopen() function is used to open a file in the memory. It accepts two arguments, the path of the file and the mode. In the above program, we are creating a text file data.txt in E:\ drive using write mode w. If the file already exists, it erases its content else, a new file is created and its memory address is store in the file pointer variable fp.

In case if there a problem in creating or opening the file then a NULL character is returned and stored in the file pointer variable pf.

The fclose() function is used to close the file which is opened in the memory. It accepts the file pointer variable to close the file.

Open an existing file

The program given below demonstrates how we can open an existing text file.

Example

#include <stdio.h>
#include <conio.h>

int main()
{
    FILE *fp;

    fp = fopen("E:/data.txt", "r");
    if(fp == NULL)
    {
        printf("Cannot open file");
        exit(0) ;
    }

    fclose(fp);
    return 0;
}

In the above program, we have opened the file data.txt for reading only using the read mode r.

Write to a file

The program given below demonstrates how we can write some text in a text file.

Example

#include <stdio.h>
#include <conio.h>

int main()
{
    FILE *fp;
    char str[100];

    fp = fopen("E:/data.txt", "a+");
    if(fp == NULL)
    {
        puts("Cannot open file");
        exit(0) ;
    }
    printf("\nEnter a few lines of text:\n");
    while(strlen(gets(str)) > 0)
    {
        fputs(str, fp);
        fputs("\n", fp);
    }

    fclose(fp);
    return 0;
}

In the above program, we have used a character array str of size 100 to store whatever we write on the screen using gets() function.

With help of while loop we are checking if the length of the str is greater than 0 then write all the contents of str into the file using the puts() function. After that we write a new line character \n into the file to break the line.

The while loop stops working when we press the enter key from the keyboard twice without writing anything on the screen. In this case the length of str becomes 0 and the loop terminates.

We close the file using fclose() function after the while loop terminates.

Read from a file

We can read the content of a file in two different ways. Let's see both ways of reading the file using the examples below.

Example 1 - using fgetc() function

#include <stdio.h>
#include <conio.h>

int main()
{
    FILE *fp;
    char ch;
    fp = fopen("E:/data.txt", "r") ;
    if(fp == NULL)
    {
        puts("cannot open file") ;
        exit(0) ;
    }

    while(1)
    {
        ch = fgetc(fp) ;
        if(ch == EOF)
        {
            break ;
        }
        printf("%c", ch) ;
    }

    fclose(fp);
    return 0;
}

In the above program, we have run an infinite while loop to read all the characters from the file until we get the end of file character EOF. We have used the fgetc() function to read individual characters from the file one by one. When we get the EOF character from the file, the while loop terminates.

Example 2 - using fgets() function

#include <stdio.h>
#include <conio.h>

int main()
{
    FILE *fp;
    char str[50];
    fp = fopen("E:/data.txt", "r") ;
    if(fp == NULL)
    {
        puts("cannot open file") ;
        exit(0) ;
    }

    while(fgets(str,50,fp)!=NULL)
    {
        printf("%s",str) ;
    }

    fclose(fp);
    return 0;
}

In the above program, we have used a while loop that uses the fgets() function to read 50 characters from the file until it finds NULL. The characters are stored in the character array str and thus printed on the screen. We can increase the size of the character array str as per how many characters we want to read from the file at a time.

Copy a file from one location to another

The program given below demonstrates how to copy a file from one location to another.

Example

#include <stdio.h>
#include <conio.h>

int main()
{
    FILE *fs, *fd;
    char ch ;

    fs = fopen("E:/data.txt", "r");
    if(fs == NULL)
    {
        puts("Cannot open source file");
        exit(0);
    }

    fd = fopen("d:/data.txt", "w");
    if(fd == NULL)
    {
        puts("Cannot open target file");
        fclose(fs);
        exit(0);
    }

    while(1)
    {
        ch = fgetc(fs);
        if(ch == EOF)
        {
            break;
        }
        else
        {
            fputc(ch, fd);
        }
    }

    fclose(fs);
    fclose(fd);
    return 0;
}

In the above program, we have used two file pointer variables *fs (file source) and *fd (file destination). With the help of while loop, we read individual characters from the source file using the file pointer fs. If the character is not an EOF character, then we write the character into the destination file using the function fputc(). When the loop terminates, we close both the files using the fclose() function.

Rename a file

The program given below demonstrates how to rename a file.

Example

#include <stdio.h>
#include <conio.h>

int main()
{
    rename("E:/data.txt", "E:/data2.txt");
    printf("File renamed successfully");
    return 0;
}

Note: Before renaming the file, make sure that the file is closed else it cannot be renamed.

Delete a file

The program given below demonstrates how to delete a file.

Example

#include <stdio.h>
#include <conio.h>

int main()
{
    remove("E:/data2.txt");
    printf("File Deleted Successfully");
    return 0;
}

Note: Before deleting the file, make sure that the file is closed else it cannot be deleted.

File Pointer Movements

We can move file pointer associated with a file to a specific position in the file using the function fseek(). The syntax of the function is given below.

fseek() Syntax

fseek(file_pointer, number_of_bytes, from_position);
  • file_pointer: It is a file pointer that points to a file in the memory.
  • number_of_bytes: It specifies the number of bytes the file pointer should move forward in the file. Negative value moves the file pointer backward.
  • from_position: It specifies the position in the file from where the file pointer should move forward or backward. There are three types of position and they are:
    SEEK_END: It place the pointer to the end of the file.
    SEEK_SET: It place the pointer to the beginning of the file.
    SEEK_CUR: It moves the pointer from its current position in the file.

Example

#include <stdio.h>
#include <conio.h>
#include <string.h>


int main()
{
    FILE *fp;
    char str[50];
    fp = fopen("e:/data.txt", "w+");
    if(fp == NULL)
    {
        printf("Cannot open file");
        exit(0) ;
    }

    // writing some text in the file
    fputs("I am learning C Programming from dremendo.com",fp);

    // move the file pointer from the beginning of the file to 5th character
    fseek(fp,5,SEEK_SET);

    // now read 10 characters including null from the current position of the file pointer
    fgets(str,10,fp);

    // print the text on the screen
    puts(str);

    // now move the file pointer 11 charaters backward from its current location
    fseek(fp,-11,SEEK_CUR);

    // now read 3 characters including null from the current position of the file pointer
    fgets(str,3,fp);

    // print the text on the screen
    puts(str);

    // now print the last 3 characters from end of the file
    fseek(fp,-3,SEEK_END);
    fgets(str,4,fp);
    puts(str);

    fclose(fp);
    return 0;
}

Output

learning
am
com