C Program to Delete a Specific Line from File

This C program demonstrates how to delete a specific line from a file. It takes the filename and the line number as input from the user and deletes the corresponding line from the file.

Problem statement

Given a file and a line number, write a C program to delete the specified line from the file.

C Program to Delete a Specific Line from File

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

void deleteLineFromFile(const char* filename, int lineNum) {
    // Function to delete a specific line from a file
    // ...

int main() {
    const char* filename = "example.txt";
    int lineNum;

    printf("Enter the line number to delete: ");
    scanf("%d", &lineNum);

    deleteLineFromFile(filename, lineNum);

    return 0;
}

How it works?

  1. The program defines a function deleteLineFromFile that takes the filename and line number as parameters.
  2. It opens the input file in read mode and a temporary file in write mode.
  3. The program reads each line from the input file and writes all lines except the line to be deleted into the temporary file.
  4. After reading all lines, it closes both files and deletes the original file.
  5. Finally, it renames the temporary file to the original file name, effectively replacing the original file with the modified version.
  6. In the main function, the program prompts the user to enter the line number to delete.
  7. It calls the deleteLineFromFile function with the provided filename and line number.

Input/output

Share:

Leave A Reply

Your email address will not be published. Required fields are marked *

You May Also Like

This C program calculates the volume and surface area of a sphere using its radius. A sphere is a three-dimensional...
This C program converts a Roman numeral to a decimal number. Roman numerals are a system of numerical notation used...
This C program calculates the value of sin(x) using the Taylor series expansion. The Taylor series expansion is a mathematical...