C program to replace the specified line in an existing text file

Here, we are going to learn how to replace the specified line in an existing text file using C program? By Nidhi Last updated : March 10, 2024

Problem statement

Read the line number from the user, and then replace the content-specific line with new text in the existing file. Then print the modified content file.

C program to replace the specified line in an existing 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 replace the specified line
// in an existing text file

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

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

    char ch;

    int line = 0;
    int temp = 1;
    int flag = 0;

    char newText[32] = "\nMy New Line";

    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 replace the line: ");
    scanf("%d", &line);
    fflush(stdout);

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

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

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

        if (temp != line) {
            putc(ch, fp2);
        }
        if (flag == 0 && temp == line) {
            fwrite(newText, 1, strlen(newText), fp2);

            flag = 1;
        }
    }

    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 replace the line: 4

Modified file:
This is Line1
This is Line2
This is Line3
My New Line
This is Line5

Explanation

Here, we read and print the content of an existing file. Then read the line number from the user to replace the line from new content in the existing file. After that, we printed the modified content file.

C File Handling Programs »

Related Programs

Comments and Discussions!

Load comments ↻





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