There is no magic formula to delete a line from a text file in C programming language. If you have to remove some specific line from the text file, you have to read the whole text, and copy it in another text file, till you reach the line you want to delete it. Don’t copy this line to another text file and continue with the remaining lines.

It may seem like a whole-lot-of work, but it is not.

Delete from a text file using C

#include<stdio.h>
int main(){

    FILE *fptr1, *fptr2;
    char file1[] ="file1.txt";
    char file2[] ="file2.txt";
    char curr;
    int del, line_number = 0;

    printf("Please enter the line number you want to delete : ");
    scanf("%d", &del);
    fptr1 = fopen(file1,"r");
    fptr2 = fopen(file2, "w");

    curr = getc(fptr1);
    if(curr!=EOF) {line_number =1;}
    while(1){
      if(del != line_number)
        putc(curr, fptr2);
        curr = getc(fptr1);
        if(curr =='\n') line_number++;
        if(curr == EOF) break;
    }
    fclose(fptr1);
    fclose(fptr2);

}

Code explanation

Get the number of the line you want to delete from the user as input. Now open the file that you want to delete the line from.

    fptr1 = fopen(file1,"r");
    fptr2 = fopen(file2, "w");

Read the whole file character by character to find the new line character.

    curr = getc(fptr1);

As you reach the newline character, increment the number of line variable, so you have a clear idea about the line you want to delete. Copy paste the whole text until you reach the line intend to be deleted.

 while(1){
      if(del != line_number)
        putc(curr, fptr2);
        curr = getc(fptr1);
        if(curr =='\n') line_number++;
        if(curr == EOF) break;
    }

The while loop has 1(truth condition) which makes it loop till it reaches the EOF character and then it breaks out of the while loop.

At the end of the program execution, close both files and remove the original file using remove() function.

Recommended reading

Last modified: March 22, 2019