Practice Programs in C: File-Based Student Records & Read/Write Text Files


This tutorial provides practical C programming exercises for file handling, including creating student records stored in a file and reading/writing text files. These examples help beginners implement persistent data storage in real-world applications.

1. File-Based Student Records

Program Description: Create a student record system that stores student details in a file and retrieves them.


#include <stdio.h>
#include <string.h>

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

int main() {
FILE *fp;
Student s;
int n;

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

// Open file for writing
fp = fopen("students.txt", "w");
if(fp == NULL) {
printf("Error opening file.\n");
return 1;
}

// Input and write student details to file
for(int i = 0; i < n; i++) {
printf("\nEnter ID, Name, Marks for student %d: ", i+1);
scanf("%d", &s.id);
scanf(" %[^\n]", s.name);
scanf("%f", &s.marks);

fprintf(fp, "%d %s %.2f\n", s.id, s.name, s.marks);
}
fclose(fp);

// Open file for reading
fp = fopen("students.txt", "r");
if(fp == NULL) {
printf("Error opening file.\n");
return 1;
}

printf("\nStudent Records from File:\n");
while(fscanf(fp, "%d %s %f", &s.id, s.name, &s.marks) != EOF) {
printf("ID: %d, Name: %s, Marks: %.2f\n", s.id, s.name, s.marks);
}
fclose(fp);

return 0;
}

Sample Output:


Enter number of students: 2

Enter ID, Name, Marks for student 1: 101 Muni 95.5
Enter ID, Name, Marks for student 2: 102 Pooja 88.0

Student Records from File:
ID: 101, Name: Muni, Marks: 95.50
ID: 102, Name: Pooja, Marks: 88.00

2. Read and Write Text Files

Program Description: Demonstrates writing and reading lines of text to and from a file.


#include <stdio.h>

int main() {
FILE *fp;
char line[100];

// Write to file
fp = fopen("example.txt", "w");
if(fp == NULL) {
printf("Error opening file.\n");
return 1;
}

fputs("Hello, this is line 1.\n", fp);
fputs("This is line 2.\n", fp);
fclose(fp);

// Read from file
fp = fopen("example.txt", "r");
if(fp == NULL) {
printf("Error opening file.\n");
return 1;
}

printf("Contents of example.txt:\n");
while(fgets(line, sizeof(line), fp) != NULL) {
printf("%s", line);
}
fclose(fp);

return 0;
}

Sample Output:


Contents of example.txt:
Hello, this is line 1.
This is line 2.

Key Points to Remember

  1. Use fprintf and fscanf for formatted data I/O
  2. Use fputs and fgets for string-based data I/O
  3. Always close files after reading/writing using fclose()
  4. File handling allows persistent storage, which is essential for real-world applications
  5. Combine structures with file I/O for efficient record management