Delete a Line from a Text File — C File Handling Solution
  • Twitter
  • Facebook
  • Snapchat
  • Instagram

C Program to Delete a Specific Line from a Text File

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.

C program to delete a specific line from a text file using a temporary file, fgets, fputs, remove, and rename, with step-by-step explanation.

📝 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:

  1. Ask for the filename and the line number to delete (1-based indexing).
  2. Open the original file in read mode ("r").
  3. Open a temporary file in write mode ("w") — call it something like temp.txt.
  4. Read the original line by line with fgets(), keeping a line counter.
  5. Write every line except the target to the temporary file with fputs().
  6. Close both files so all buffered data is flushed to disk.
  7. Delete the original with remove(), then rename the temporary file to the original filename with rename().

💻 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:

Contents of 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:

Console: Enter the filename: sample.txt
Enter the line number to delete: 2
Line 2 deleted successfully from 'sample.txt'.

After the program finishes, sample.txt contains:

Contents of 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.
⚠️ Important: Do not call 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 fclose before renaming: On Windows, rename fails if either file is still open. Always close both handles first.
  • Losing the trailing newline: fputs preserves whatever fgets gives 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_line is 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. The deleted flag prevents unnecessary replacement.
  • Temp file collision: If temp.txt already exists with content you wanted to keep, this program overwrites it. A more robust version uses a random temp name like tmpfile() or appends a PID to the name.

💡 Tips & Best Practices

  • Always verify that both fopen calls returned a valid pointer.
  • Check the return value of remove and rename — both return 0 on success and non-zero on failure.
  • For a more robust temp file, use tmpfile() or generate a unique name with tmpnam().
  • Compile with gcc -Wall -Wextra -std=c11 -g to catch unused variables and type mismatches.

📖 Related Tutorials in This Series

  • File Handling Assignments — Complete Index
  • 1. Create a New Text File and Write Text in It
  • 4. Read and Display the Contents of a Text File
  • 5. Count Characters, Words, and Lines in a Text File
  • 10. Replace a Word with Another Word in a Text File
  • 15. Copy the Contents of One Text File into Another
  • Files FAQ

Previous Problem: -->> 5. Count Characters, Words, and Lines in a Text File   ||   Next Problem: -->> 7. Write Data to a Binary File

Back to Index: -->> File Handling Assignments in C


C Language

  • Home
  • Why C Language
  • History of C Language
  • Applications of C Language
  • Introduction To C
    • What is Program?
    • Structure of C Program
    • Working Of C Program
    • CHARACTER SET
    • VARIABLES AND IDENTIFIERS
    • BUILT-IN DATA TYPES
    • OPERATORS AND EXPRESSIONS
    • CONSTANTS AND LITERALS
    • SIMPLE ASSIGNMENT STATEMENT
    • BASIC INPUT/OUTPUT STATEMENT
    • SIMPLE 'C' PROGRAMS
    • Assignments
  • Operators in C Programming
    • Arithmetic Operators
    • Assignment Operators
    • Increment and Decrement Operators
    • Relational Operators
    • Logical Operators
    • Bitwise Operators
    • Other Operators
    • Assignments
  • CONDITIONAL STATEMENTS
    • DECISION MAKING WITHIN A PROGRAM
    • CONDITIONS
    • IF STATEMENT
    • IF-ELSE STATEMENT
    • IF-ELSE LADDER
    • NESTED IF-ELSE
    • SWITCH CASE
    • Assignments
  • LOOPS STATEMENTS
    • Introduction to Loops
    • GO TO Statement
    • Do while Loop
    • While Loop
    • Nested While Loop
    • Difference Between While and Do while
    • Difference Between Goto and loop
    • while loop assignments
    • C FOR Loop
    • C For loop examples
    • Nested for loop
    • Nested for loop examples
    • Infinite while Loops
    • Infinite for Loops
    • Continue in Loops
    • break in Loops
    • difference while do..while & for
    • Assignments
  • Arrays
    • One Dimensional Array
    • Declaring 1D Arrays
    • Initilization of 1D arrays
    • Accessing element of one 1D Array
    • Read and Display 1D Arrays
    • Two Dimensional Arrays
    • Declare 2D Arrays
    • Read and Display 2D Arrays
    • Assignments/Examples
  • Functions
    • Introduction
    • Need For User-Defined Function
    • Multiple Function Program
    • Modular Programming
    • Elements Of User Defined Function
    • Function Definition
    • Function Declaration
    • Types of functions
    • Nesting of Function
    • Recursion
    • Passing Array To Functions
    • Scope,Visibility and Lifetime of Variables
    • Assignments
  • Structure
    • Introduction
    • Array vs Structure
    • Defining Structure
    • Declaring Structure Variables
    • Type Defined Structure
    • Accessing Structure Members
    • Structure Initilization
    • Copying & Comparing Structure Variables
    • Array of Structure
    • Arrays Within Structure
    • Structures Within Structures
    • Structures and Functions
    • Structure Examples/Assignments
  • Union
    • Define Union
    • Create and use Union
    • Difference Between Structure and Union
    • Union Examples
    • Union FAQ
  • Pointers
    • What Are Pointers In C?
    • How Do We Use Pointers In C?
    • Declaration Of A Pointer
    • The Initialization Of A Pointer
    • Syntax Of Pointer Initialization
    • Use Of Pointers In C
    • The Pointer To An Array
    • The Pointer To A Function
    • The Pointer To A Structure
    • Types Of Pointers
    • The Null Pointer
    • The Void Pointer
    • The Wild Pointer
    • The Near Pointer
    • The Huge Pointer
    • The far Pointer
    • dangling pointer
    • Accessing Pointers- Indirectly And Directly
    • Pros Of Using Pointers In C
    • Cons Of Pointers In C
    • Applications Of Pointers In C
    • The & Address Of Operator In C
    • How To Read The Complex Pointers In C?
    • Practice Problems On Pointers
  • File Processiong
    • File Handling In C
    • Types Of Files In C
    • Operations Done In File Handling
    • File Examples
    • Binary Files
    • count words,lines in a file
    • Copy files
    • Update File
    • count vowels in a file
  • Preprocessor
    • Macro substitution division
    • File Inclusion
    • Conditional Compilation
    • Other directives
    • Examples
  • Dynamic Memory Allocation
    • malloc
    • calloc
    • free
    • realloc
    • Examples
  • Storage Classes
  • Graphics
  • Frequently Asked Interview Questions (FAQ)
    • Introduction To C FAQ
    • Operators FAQ
    • Conditional Statements FAQ
    • Loops FAQ
    • Arrays FAQ
    • Function FAQ
    • Structure FAQ
    • Pointers FAQ
    • Files FAQ
    • Storage classes FAQ
    • Dynamic Memory FAQ
  • Programs/Assignments
    • Introduction To C
    • Operators
    • Conditional Statements
    • Loops
    • Arrays
    • Function
    • Structure
    • Pointers
    • Files
    • Storage classes
    • Dynamic Memory
  • Case Studies
  • Multiple Choice Questions
    • Introduction To C MCQ
    • Operators MCQ
    • Conditional Statements MCQ
    • Loops MCQ
    • Arrays MCQ
    • Function MCQ
    • Structure MCQ
    • Pointers MCQ
    • Files MCQ
    • Storage classes MCQ
    • Dynamic Memory MCQ
    • More MCQ

Get in touch

  • tech2dsm@gmail.com

© Sankalan Data Tech. All rights reserved.