C program to remove a specific line from the text file

Here, we are going to learn how to remove a specific line from the text file using C program? By Nidhi Last updated : March 10, 2024

Problem statement

Read the line number from the user, and delete the specific line from the existing file. Then print the modified content file.

C program to remove a specific line from the text file

The source code to remove a specific line from the text file is given below. The given program is compiled and executed using GCC compile on UBUNTU 18.04 OS successfully.

// C program to remove a specific line from
// the text file

#include <stdio.h>

int main()
{
    FILE* fp1;
    FILE* fp2;

    char ch;

    int line = 0;
    int temp = 1;

    fp1 = fopen("includehelp.txt", "r");
    if (fp1 == NULL) {
        printf("\nUnable to open file\n");
        return -1;
    }

    while (!feof(fp1)) {
        ch = getc(fp1);
        printf("%c", ch);
    }
    rewind(fp1);

    printf("\nEnter line number to delete the line: ");
    scanf("%d", &line);

    fp2 = fopen("temp.txt", "w");

    while (!feof(fp1)) {
        ch = getc(fp1);

        if (ch == '\n')
            temp++;

        if (temp != line)
            putc(ch, fp2);
    }

    fclose(fp1);

    fclose(fp2);

    remove("includehelp.txt");
    rename("temp.txt", "includehelp.txt");

    printf("\nModified file:\n");

    fp1 = fopen("includehelp.txt", "r");
    if (fp1 == NULL) {
        printf("\nUnable to open file\n");
        return -1;
    }

    while (!feof(fp1)) {
        ch = getc(fp1);
        printf("%c", ch);
    }

    fclose(fp1);

    printf("\n");

    return 0;
}

Output

This is Line1
This is Line2
This is Line3
This is Line4
This is Line5
Enter line number to delete the line: 2
Modified file:
This is Line1
This is Line3
This is Line4
This is Line5

Explanation

Here, we read and print the content of an existing file. Then read the line number from the user to delete the line from the existing file. After that, we copied the content of the existing file to a temporary file except for a specific line. Then remove the existing file and rename the temporary file with the name of the existing file. At last, we printed the modified content of the file.

C File Handling Programs »


Related Programs

Comments and Discussions!

Load comments ↻






Copyright © 2024 www.includehelp.com. All rights reserved.