#include <stdio.h> int main() { char name[50]; int marks, i,n; printf(“Enter number of students”); scanf(“%d”, &n); FILE *fptr; fptr=(fopen(“C:\\student.txt”,”a”)); if (fptr==NULL){ printf("Error!"); exit(1); } for(i=0;i<n;++i) { printf("For student%d\nEnter name: ",i+1); scanf("%s",name); printf(“Enter marks”); scanf(“%d”, &marks); fprintf(fptr, “\nName: %s\nMarks=%d\n”, name, marks); } fclose(fptr); Return 0; }
1. Include Directives
#include <stdio.h>
: Includes the Standard Input Output library, allowing you to use functions like printf
, scanf
, and file handling functions.2. Main Function
int main() {
- This defines the
main
function, which is the entry point of the program.
3. Variable Declarations
char name[50]; // Array for student names int marks, i, n; // Marks, loop index, number of students
char name[50]
: An array to store student names (up to 49 characters plus a null terminator).int marks
: Variable to store each student’s marks.int i, n
:i
is used for looping, andn
stores the number of students.
4. User Input
printf("Enter number of students: "); scanf("%d", &n);
- Prompts the user to enter the number of students and reads that value into
n
.
5. File Handling
FILE *fptr; // Declare a file pointer fptr = fopen("C:\\student.txt", "a"); // Open file in append mode
A file pointer
fptr
is declared, and fopen
is used to open student.txt
in append mode ("a"
). This allows new entries to be added to the end of the file.6. Error Checking
if (fptr == NULL)
{
printf("Error!");
exit(1);
}
Checks if the file was successfully opened. If
fptr
is NULL
, it indicates a failure to open the file, and the program prints an error message and exits with a status of 1
.7. Input Loop
for (i = 0; i < n; ++i)
{
printf("For student %d\nEnter name: ", i + 1);
scanf("%s", name);
printf("Enter marks: ");
scanf("%d", &marks);
fprintf(fptr, "\nName: %s\nMarks = %d\n", name, marks);
}
This loop runs
n
times to gather input for each student:- It prompts the user for the name and reads it into the
name
array. - It then prompts for the student’s marks and stores that in
marks
. - Finally, it writes the name and marks to the file using
fprintf
.
8. Closing the File
fclose(fptr);
- Closes the file after all student data has been written, ensuring that all data is saved properly.
9. Return Statement
return 0;
- Indicates that the program completed successfully.