Read name and marks of students and store them in a file. If the file previously exits, add the information to the file

Write a program to read names and marks of n number of students and store them in a file.
 
If the file previously exits, add the information to the file.


C Program


#include <stdio.h>

int main()
{

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

    printf("Enter number of student: ");
    scanf("%d", &n);
    FILE *studentRecord;

    // open file in qppend mode mode
    studentRecord = fopen("studentrecord.txt""a");
    for (int i = 1; i <= n; i++)
    {
        //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", name, marks);
        fputs(buffer, studentRecord);
    }
    //close the file
    fclose(studentRecord);

    return 0;
}

Input File: studentrecord.txt

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

Enter number of student: 2
Please enter student 1 name: Jeet
Please enter student 1 marks: 56
Please enter student 2 name: Anuj
Please enter student 2 marks: 67

Output File: studentrecord.txt

Name = Rahul, marks = 67 Name = Rohit, marks = 34 Name = Suman, marks = 65 Name = Jeet, marks = 56 Name = Anuj, marks = 67


No comments:

Post a Comment