In this tutorial, you'll learn how to delete a specific line from a text file using the C programming language. Unlike reading or writing, deleting from a file isn't a single operation — you can't "cut" a line out of the middle. The standard approach is to copy every line except the target into a temporary file, then replace the original with the temporary file using remove() and rename(). This technique is the foundation of every file-editing utility you'll build.
📝 Problem Statement
Write a program in C to delete a specific line from a text file.
⚙️ How the Program Works
The program follows the standard "copy-and-replace" pattern:
- Ask for the filename and the line number to delete (1-based indexing).
- Open the original file in read mode (
"r"). - Open a temporary file in write mode (
"w") — call it something liketemp.txt. - Read the original line by line with
fgets(), keeping a line counter. - Write every line except the target to the temporary file with
fputs(). - Close both files so all buffered data is flushed to disk.
- Delete the original with
remove(), then rename the temporary file to the original filename withrename().
💻 Complete C Program
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
FILE *src, *tmp;
char filename[100];
char line[1024];
int target_line, current_line = 1;
int deleted = 0;
printf("Enter the filename: ");
scanf("%99s", filename);
printf("Enter the line number to delete: ");
scanf("%d", &target_line);
src = fopen(filename, "r");
if (src == NULL)
{
printf("Error: Could not open file '%s'.\n", filename);
return 1;
}
tmp = fopen("temp.txt", "w");
if (tmp == NULL)
{
printf("Error: Could not create temporary file.\n");
fclose(src);
return 1;
}
/* Copy every line except the target to temp.txt */
while (fgets(line, sizeof(line), src) != NULL)
{
if (current_line != target_line)
fputs(line, tmp);
else
deleted = 1;
current_line++;
}
fclose(src);
fclose(tmp);
if (!deleted)
{
printf("Line %d not found. File unchanged.\n", target_line);
remove("temp.txt");
return 0;
}
/* Replace the original file with the temporary one */
if (remove(filename) != 0)
{
printf("Error: Could not remove the original file.\n");
return 1;
}
if (rename("temp.txt", filename) != 0)
{
printf("Error: Could not rename temporary file to '%s'.\n", filename);
return 1;
}
printf("Line %d deleted successfully from '%s'.\n", target_line, filename);
return 0;
}🖥️ Sample Output
Assume sample.txt contains:
sample.txt before:
Line 1: Hello, World!Line 2: This text was written using fprintf.
Line 3: File handling in C is fun!
Line 4: The quick brown fox jumps over the lazy dog.
Running the program to delete line 2:
Enter the line number to delete: 2
Line 2 deleted successfully from 'sample.txt'.
After the program finishes, sample.txt contains:
sample.txt after:
Line 1: Hello, World!Line 3: File handling in C is fun!
Line 4: The quick brown fox jumps over the lazy dog.
🔍 Line-by-Line Explanation
| Line / Code | Explanation |
|---|---|
#include <stdlib.h> |
Provides remove and rename. |
fopen(filename, "r") |
Opens the source file for reading. |
fopen("temp.txt", "w") |
Creates a new temporary file for writing. If temp.txt already exists in the working directory, it is truncated. |
while (fgets(...) != NULL) |
Reads one line at a time until the end of file. |
if (current_line != target_line) fputs(line, tmp); |
Every line except the target is copied verbatim — including its trailing newline. |
deleted = 1; |
Flag that tells us whether the target line was actually found. If it wasn't, we don't replace the original file. |
fclose(src); fclose(tmp); |
Flush buffers and close both files before calling remove and rename — otherwise the rename may fail on Windows. |
remove(filename) |
Deletes the original file. Returns 0 on success. |
rename("temp.txt", filename) |
Renames the temporary file to the original name, effectively replacing it. |
fclose on src and then fopen the same file in write mode — that would truncate the file before you've written the replacement. The temp-file approach exists precisely to avoid that.
🧠 Why a Temporary File Is Necessary
A file in C is a sequence of bytes. Deleting from the middle of a file would require shifting all subsequent bytes backwards by the length of the deleted line — an operation that C's standard library doesn't provide directly, and that is error-prone when done manually. The temp-file approach is the safe, portable solution:
- The source file is opened read-only — never truncated while we still need its data.
- The replacement is built in a fresh file, so if the program crashes mid-way, the original is untouched.
- Only after the copy succeeds do we swap files — an atomic operation on most filesystems.
The same pattern underlies sed -i, in-place editors, and almost every file-modification tool in Unix.
🐛 Common Pitfalls
- Off-by-one line numbering: Users think of "line 1" as the first line, but if you start the counter at 0 you'll delete the wrong line. This program starts at 1 and matches user expectation.
- Forgetting to
fclosebefore renaming: On Windows,renamefails if either file is still open. Always close both handles first. - Losing the trailing newline:
fputspreserves whateverfgetsgives you, including the newline, so no special handling is needed. But if a line has no trailing newline (last line of file), the file may merge lines after a deletion — check this behavior with your test files. - Target line doesn't exist: If
target_lineis greater than the number of lines, nothing is copied incorrectly — but the temporary file is a perfect copy of the original, and replacing would be wasteful. Thedeletedflag prevents unnecessary replacement. - Temp file collision: If
temp.txtalready exists with content you wanted to keep, this program overwrites it. A more robust version uses a random temp name liketmpfile()or appends a PID to the name.
💡 Tips & Best Practices
- Always verify that both
fopencalls returned a valid pointer. - Check the return value of
removeandrename— both return 0 on success and non-zero on failure. - For a more robust temp file, use
tmpfile()or generate a unique name withtmpnam(). - Compile with
gcc -Wall -Wextra -std=c11 -gto catch unused variables and type mismatches.