C Programs | IT Developer
IT Developer

C Programs



Share with a Friend

File Handling in C

Delete student record from file

C Program: Delete student record from file

C

#include <stdio.h>

#include <stdlib.h>

 

struct Student {

    int roll;

    char name[50];

    float marks;

};

 

int main() {

    FILE *file, *temp;

    struct Student s;

    int roll, found = 0;

 

    file = fopen("students.txt", "r");

    temp = fopen("temp.txt", "w");

 

    if (file == NULL) {

        printf("No student records found!\n");

        return 0;

    }

 

    printf("Enter Roll Number of the Student to Delete: ");

    scanf("%d", &roll);

 

    while (fscanf(file, "%d %s %f", &s.roll, s.name, &s.marks) != EOF) {

        if (s.roll == roll) {

            found = 1;

            printf("Record deleted: Roll=%d, Name=%s, Marks=%.2f\n", s.roll, s.name, s.marks);

            continue; // skip writing this record to temp file

        } else {

            fprintf(temp, "%d %s %.2f\n", s.roll, s.name, s.marks);

        }

    }

 

    fclose(file);

    fclose(temp);

 

    remove("students.txt");

    rename("temp.txt", "students.txt");

 

    if (!found)

        printf("No record found with Roll Number %d\n", roll);

    else

        printf("Record deleted successfully!\n");

 

    return 0;

}

Output

 
 
Before  (students.txt):
1 Alice 85.5
2 Bob 78.0
3 Charlie 90.0

Input: 
Enter Roll Number of the Student to Delete: 2

After  (students.txt):

1 Alice 85.5
3 Charlie 90.0

Explanation: How It Works

  1. Opens the students.txt file (for reading existing data).
  2. Creates a temporary file temp.txt.
  3. Reads each record:
    • If the roll number matches → skips writing it (deletes record).
    • If not → copies it to temp.txt.
  4. Deletes the original file and renames the temp file.