7.DS - Lab -C Program to create a file to store student records(Part A)

 C Program to create a file to store student records

ALGORITHM :

Step 1: Start
Step 2: Create a file named "student_records.txt".
Step 3: Open the file in write mode as file.
Step 4: Input the number of students (num_students).
Step 5: For each student, input their name, roll number, and marks.
Step 6: Write the student's details (name, roll number, and marks) to the file, separated by commas, followed by a newline character.
Step 7: Close the file after adding all student records.
Step 8: End

SOURCE CODE : 

#include <stdio.h>

struct Student {
    char name[50];
    int rollNo;
    float marks;
};

int main() {
    FILE *file;
    file = fopen("student_records.txt", "w");

    if (file == NULL) {
        printf("Error opening the file.\n");
        return 1;
    }

    int n;
    printf("Enter the number of students: ");
    scanf("%d", &n);

    struct Student student;

    for (int i = 0; i < n; i++) {
        printf("\nEnter details for Student %d:\n", i + 1);
        printf("Name: ");
        scanf("%s", student.name);
        printf("Roll No: ");
        scanf("%d", &student.rollNo);
        printf("Marks: ");
        scanf("%f", &student.marks);

        fprintf(file, "Name: %s, Roll No: %d, Marks: %.2f\n", student.name, student.rollNo, student.marks);
    }

    fclose(file);
    return 0;
}


OUTPUT : A file "student_records.txt" will be created with the student details. 
Then execute this. 

Enter the number of students: 2

Enter details for Student 1:
Name: John Doe
Roll No: 101
Marks: 85.5

Enter details for Student 2:
Name: Jane Smith
Roll No: 102
Marks: 78.0

No comments:

Post a Comment