Read name and marks of n students and store them in a file

Write a program to read names and marks of n number of students and store them in a file.

C Program


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

int main()

{

    char name[50];
    int marks;
    int n;
    char buffer[32] = {0};

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

    FILE *studentRecord;

    //open file in write mode
    studentRecord = fopen("studentrecord.txt""w");
    if (studentRecord == NULL)
    {
        printf("Please create file\n");
        exit(1);
    }

    for (int i = 1i <= ni++)
    {
        //scan the name of student
        printf("Please enter student %d name: "i);
        scanf("%s", &name);

        //scan the marks of student
        printf("Please enter student %d marks: "i);
        scanf("%d", &marks);

        sprintf(buffer"Name = %s, marks = %d\n"namemarks);
        fputs(bufferstudentRecord);
    }

    //close the file
    fclose(studentRecord);
    return 0;
}

Input:

Enter number of students: 3
Please enter student 1 name: Rahul
Please enter student 1 marks: 67
Please enter student 2 name: Rohit
Please enter student 2 marks: 34
Please enter student 3 name: Suman
Please enter student 3 marks: 65
Output File:studentrecord.txt

Name = Rahul, marks = 67 Name = Rohit, marks = 34 Name = Suman, marks = 65


No comments:

Post a Comment