C program to replace specific line in a text file

Quick links

Write a C program to input line number and replace specific line with another in text file. How to replace specific line in a text file in C programming. Logic to replace specific line with another in a text file in C program.

Required knowledge

Basic Input Output, String, File handling

Logic to replace specific line in a text file

Step by step descriptive logic to replace specific line with another in a text file.

  1. Open source file in read mode, store its reference to fPtr.
  2. Create and open a temporary file with name replace.tmp, store its reference to fTemp.
  3. Input line number to replace in file from user. Store it in some variable say line.
  4. Input new line from user to replace with, store it in newline.
  5. Initialize a count variable with 0.
  6. Read a line from file and store it in buffer.
  7. Increment count by 1.
  8. If count == line, then current line should be replaced with newline. Means if (count == 0) then write newline to fTemp, otherwise write buffer to fTemp.
  9. Repeat step 6-8 till end of file.
  10. Finally close all files.
  11. Delete the original source file and rename temporary fTemp file path as of source file.

Program to replace specific line in a text file

/**
 * C program to replace a specific line with another in a file.
 */

#include <stdio.h>
#include <stdlib.h>

#define BUFFER_SIZE 1000


int main()
{
    /* File pointer to hold reference of input file */
    FILE * fPtr;
    FILE * fTemp;
    char path[100];
    
    char buffer[BUFFER_SIZE];
    char newline[BUFFER_SIZE];
    int line, count;


    printf("Enter path of source file: ");
    scanf("%s", path);

    printf("Enter line number to replace: ");
    scanf("%d", &line);

    /* Remove extra new line character from stdin */
    fflush(stdin);

    printf("Replace '%d' line with: ", line);
    fgets(newline, BUFFER_SIZE, stdin);


    /*  Open all required files */
    fPtr  = fopen(path, "r");
    fTemp = fopen("replace.tmp", "w"); 

    /* fopen() return NULL if unable to open file in given mode. */
    if (fPtr == NULL || fTemp == NULL)
    {
        /* Unable to open file hence exit */
        printf("\nUnable to open file.\n");
        printf("Please check whether file exists and you have read/write privilege.\n");
        exit(EXIT_SUCCESS);
    }


    /*
     * Read line from source file and write to destination 
     * file after replacing given line.
     */
    count = 0;
    while ((fgets(buffer, BUFFER_SIZE, fPtr)) != NULL)
    {
        count++;

        /* If current line is line to replace */
        if (count == line)
            fputs(newline, fTemp);
        else
            fputs(buffer, fTemp);
    }


    /* Close all files to release resource */
    fclose(fPtr);
    fclose(fTemp);


    /* Delete original source file */
    remove(path);

    /* Rename temporary file as original file */
    rename("replace.tmp", path);

    printf("\nSuccessfully replaced '%d' line with '%s'.", line, newline);

    return 0;
}

Suppose <strong>data/file3.txt</strong> contains.

I love programming.
Programming with files is fun.
Learning C programming at Codeforwin is simple and easy.

After executing program <strong>data/file3.txt</strong> contains.

I love programming.
---------PROGRAMMING IN C---------
Learning C programming at Codeforwin is simple and easy.

Output

Enter path of source file: data/file3.txt
Enter line number to replace: 2
Replace '2' line with: ---------PROGRAMMING IN C---------

Successfully replaced '2' line with '---------PROGRAMMING IN C---------
'.

Happy coding 😉