Q:

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

0

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

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

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.

Program:

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.

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

File Handling Examples Programs in C language

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now
C program to append the content of one file to the... >>
<< C program to remove a specific line from the text ...