C Program to Replace a Specific Line in a Text File

In this tutorial you will learn about the C Program to Replace a Specific Line in a Text File and its application with practical example.

In this tutorial, we will learn to create c program to replace a specific line in a text file. The file must exist in the directory where the executable file of this program is present.

Prerequisites

Before starting with this tutorial we assume that you are best aware of the following C programming topics: C Pointers, C File Handling, C Strings and C Input Output.

Create required files

Let’s first create files (inside the current project directory) as following:

  • f1.txt – file to count line

The file must be saved in the folder where you are saving program file. Put the following content in the file:

f1.txt

How to Replace a Specific Line in a Text File?

The source file will be opened and being read through character by character and store its contents in temporary file. When we reached the specific line we will copy new line content to temporary file. Finally, the original source file will be deleted and the temporary file will renamed to source file name.

C Program to Replace a Specific Line in a Text File

In this C program we will replace a specific line in a text file. The source file will be opened in “read” mode and a temporary target file is opened in “write” mode. The source file (f1.txt) will be opened and being read through character by character and store its contents in temporary file. When we reached the specific line we will copy new line content to temporary file. The file being read copied until its EOF (end of file) is reached. Finally, the original source file will be deleted and the temporary file will renamed to source file name.

Output:-

C-Program-to-Replace-a-Specific-Line-in-a-Text-File

f1.txt :- After replacing line 2

Open source file in read mode, store its reference to fPtr.Create and open a temporary file with name replace.tmp, store its reference to fTemp.Input line number to replace in file from user. Store it in some variable say line.Input new line from user to replace with, store it in newline.Initialize a count variable with 0.Read a line from file and store it in buffer. Increment count by 1.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. Repeat step 6-8 till end of file.Finally close all files.Delete the original source file and rename temporary fTemp file path as of source file.

In this tutorial we have learn about the C Program to Replace a Specific Line in a Text File and its application with practical example. I hope you will like this tutorial.