C program to remove a line from the file

In C, removing a line from a file requires creating a temporary file because files cannot be modified directly in place. The process involves reading the original file line by line, copying all lines except the target line to a temporary file, then replacing the original file.

Syntax

FILE *fopen(const char *filename, const char *mode);
char *fgets(char *str, int n, FILE *stream);
int fputs(const char *str, FILE *stream);
int remove(const char *filename);
int rename(const char *oldname, const char *newname);

Algorithm

The algorithm to remove a line from a file follows these steps −

  • Step 1 − Open the source file in read mode
  • Step 2 − Create and open a temporary file in write mode
  • Step 3 − Read each line from source file with a line counter
  • Step 4 − Copy all lines except the target line to temporary file
  • Step 5 − Close both files
  • Step 6 − Delete original file and rename temporary file

Example

The following program demonstrates how to remove a specific line from a file −

Note: This program works with file operations. Create a text file named "sample.txt" in your working directory before running.

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

#define BUFFER_SIZE 1000

void deleteLine(FILE *src, FILE *temp, const int lineToRemove) {
    char buffer[BUFFER_SIZE];
    int currentLine = 1;
    
    while (fgets(buffer, BUFFER_SIZE, src) != NULL) {
        if (currentLine != lineToRemove) {
            fputs(buffer, temp);
        }
        currentLine++;
    }
}

void printFile(const char *filename) {
    FILE *file = fopen(filename, "r");
    if (file == NULL) {
        printf("Error opening file for reading.<br>");
        return;
    }
    
    char ch;
    while ((ch = fgetc(file)) != EOF) {
        putchar(ch);
    }
    fclose(file);
}

int main() {
    FILE *sourceFile, *tempFile;
    char filename[] = "sample.txt";
    char tempFilename[] = "temp.txt";
    int lineNumber;
    
    /* Create sample file for demonstration */
    sourceFile = fopen(filename, "w");
    if (sourceFile == NULL) {
        printf("Error creating sample file.<br>");
        return 1;
    }
    fprintf(sourceFile, "Line 1: Hello World<br>");
    fprintf(sourceFile, "Line 2: C Programming<br>");
    fprintf(sourceFile, "Line 3: File Operations<br>");
    fprintf(sourceFile, "Line 4: TutorialsPoint<br>");
    fclose(sourceFile);
    
    printf("Original file contents:<br>");
    printFile(filename);
    
    printf("\nEnter line number to remove (1-4): ");
    scanf("%d", &lineNumber);
    
    /* Open source file in read mode */
    sourceFile = fopen(filename, "r");
    /* Create temporary file */
    tempFile = fopen(tempFilename, "w");
    
    if (sourceFile == NULL || tempFile == NULL) {
        printf("Error opening files.<br>");
        return 1;
    }
    
    /* Remove the specified line */
    deleteLine(sourceFile, tempFile, lineNumber);
    
    /* Close both files */
    fclose(sourceFile);
    fclose(tempFile);
    
    /* Replace original file with temporary file */
    remove(filename);
    rename(tempFilename, filename);
    
    printf("\nFile contents after removing line %d:<br>", lineNumber);
    printFile(filename);
    
    return 0;
}

How It Works

The program works by implementing the following logic −

  • Line Counting: Uses a counter to track the current line number while reading
  • Conditional Copy: Copies lines to temporary file only when line number doesn't match target
  • File Replacement: Uses remove() and rename() to replace the original file
  • Buffer Management: Uses fgets() and fputs() for safe line-by-line operations

Key Points

  • Always check if files opened successfully before performing operations
  • Use fgets() instead of gets() for safe string input
  • Close all file handles before attempting to delete or rename files
  • The temporary file approach ensures data integrity during the operation

Conclusion

Removing a line from a file in C requires the temporary file technique since direct in-place editing is not supported. This method ensures safe file modification while preserving data integrity.

Updated on: 2026-03-15T14:11:05+05:30

10K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements