Index 10 SET: A
Title of the Program: C | File Handling
Objectives
Upon completion of this lab, students will be able to:
• To understand the concepts of file handling and its importance in C programming.
• To use file pointers and functions like fopen() and fclose() to manage files.
• To implement character-level I/O using getc() and putc().
• To implement integer-level I/O using getw() and putw().
• To perform formatted I/O using fprintf() and fscanf().
• To perform block-level I/O for structures using fread() and fwrite().
Requirements
• Computer System: Any standard desktop or laptop computer.
• Operating System: Windows, macOS, or Linux.
• Integrated Development Environment (IDE) / Compiler:
o Dev-C++
o Code::Blocks
o Visual Studio Code with C/C++ extensions
o GCC (GNU Compiler Collection)
Theory
File Handling in C
File handling in C allows programs to interact with files on the disk. This enables persistent storage
of data, meaning the data remains even after the program has finished running. The <stdio.h>
header file provides a set of standard library functions for file I/O.
The FILE Pointer
All file handling functions use a special pointer of type FILE. This pointer, often called a file
handle, is used to communicate with the file and track its position.
Core File I/O Functions
• fopen(): Opens a file and returns a FILE pointer. It takes the file path and mode (e.g., "r"
for read, "w" for write, "a" for append) as arguments. It returns NULL if the file cannot be
opened.
Computer Department-KMC, Bagbazar
• fclose(): Closes an open file, saving all data and releasing the file pointer.
• getc(): Reads a single character from the file.
• putc(): Writes a single character to the file.
• getw(): Reads a single integer from the file.
• putw(): Writes a single integer to the file.
• fscanf(): Reads formatted input from a file, similar to scanf().
• fprintf(): Writes formatted output to a file, similar to printf().
• fread(): Reads a block of data (e.g., a structure or an array of structures) from a binary
file.
• fwrite(): Writes a block of data to a binary file.
Procedure
Part 1: Character and Integer I/O
Problem 1: Reading and Writing a Single Character (putc, getc)
Write a C program to ask for a student's grade (e.g., 'A', 'B', 'C') and write it to a file named
grade.txt. Then, read the character back from the same file and display it on the screen.
C Program:
#include <stdio.h>
int main() {
FILE *fp;
char grade;
// Open file in write mode ("w") to write the grade
fp = fopen("grade.txt", "w");
if (fp == NULL) {
printf("Error opening file!\n");
return 1;
}
printf("Enter student's grade (A-F): ");
scanf(" %c", &grade); // Note the space before %c to consume whitespace
putc(grade, fp); // Write the character to the file
fclose(fp); // Close the file
// Open file in read mode ("r") to read the grade
fp = fopen("grade.txt", "r");
if (fp == NULL) {
printf("Error opening file!\n");
return 1;
}
grade = getc(fp); // Read a character from the file
printf("The grade read from the file is: %c\n", grade);
Computer Department-KMC, Bagbazar
fclose(fp); // Close the file
return 0;
}
Output (example):
Enter student's grade (A-F): B
The grade read from the file is: B
Problem 2: Reading and Writing a Single Integer (putw, getw)
Write a C program to store a student's roll number in a file named rollno.dat and then read it
back. Use putw() and getw().
C Program:
#include <stdio.h>
int main() {
FILE *fp;
int roll_number;
// Open file in write mode ("w") to write the integer
fp = fopen("rollno.dat", "w");
if (fp == NULL) {
printf("Error opening file!\n");
return 1;
}
printf("Enter student's roll number: ");
scanf("%d", &roll_number);
putw(roll_number, fp); // Write the integer to the file
fclose(fp); // Close the file
// Open file in read mode ("r") to read the integer
fp = fopen("rollno.dat", "r");
if (fp == NULL) {
printf("Error opening file!\n");
return 1;
}
roll_number = getw(fp); // Read an integer from the file
printf("The roll number read from the file is: %d\n", roll_number);
fclose(fp); // Close the file
return 0;
}
Computer Department-KMC, Bagbazar
Output (example):
Enter student's roll number: 101
The roll number read from the file is: 101
Problem 3: Reading and Writing string into file (fprintf(), fscanf())
Write a C program to store a string / message into a file.
C Program:
#include <stdio.h>
int main()
{
FILE *ptr;
char msz[] = "We are learning File Handling";
ptr = fopen("nepal.txt", "w");
if (ptr == NULL)
{
printf("Error opening file!\n");
return 1;
}
fprintf(ptr, "%s", msz);
fclose(ptr);
printf("Data written to file. Please check file!\n");
return 0;
} Output :
Data written to file. Please check file!
Part 2: Formatted and Block I/O
Problem 4: Formatted File I/O (fprintf(), fscanf())
Write a C program to input a student's name, roll number, and GPA. Store this data in a file
named student_info.txt using fprintf(). Then, read the data back from the file using
fscanf() and display it.
Computer Department-KMC, Bagbazar
C Program:
#include <stdio.h>
int main() {
FILE *fp;
char name[50];
int roll_no;
float gpa;
// --- Writing to the file ---
fp = fopen("student_info.txt", "w");
if (fp == NULL) {
printf("Error opening file!\n");
return 1;
}
printf("Enter student name: ");
scanf(" %[^\n]", name); // Reads until newline, including spaces
printf("Enter roll number: ");
scanf("%d", &roll_no);
printf("Enter GPA: ");
scanf("%f", &gpa);
fprintf(fp, "%s\n%d\n%.2f\n", name, roll_no, gpa); // Separate with
newlines
fclose(fp);
// --- Reading from the file ---
fp = fopen("student_info.txt", "r");
if (fp == NULL) {
printf("Error opening file!\n");
return 1;
}
fgets(name, sizeof(name), fp); // Reads the whole line (including spaces)
fscanf(fp, "%d", &roll_no);
fscanf(fp, "%f", &gpa);
printf("\n--- Student Details Read from File ---\n");
printf("Name: %s\n", name);
printf("Roll No: %d\n", roll_no);
printf("GPA: %.2f\n", gpa);
fclose(fp);
return 0;
}
Output (example):
Enter student name: Kapil Sharma
Enter roll number: 105
Enter GPA: 3.85
Computer Department-KMC, Bagbazar
--- Student Details Read from File ---
Name: Kapil Sharma
Roll No: 105
GPA: 3.85
Problem 5: Formatted File I/O-II (fprintf(), fscanf())
Write a C program to define a Student structure with roll_no, name, and gpa. The program
should:
1. Ask the user for the number of students (N).
2. Input details for N students into an array of structures.
3. Write the details of all students to a text file named students.txt using fprintf().
4. Read the data back into a new array of structures using fscanf().
5. Display the details of all students from the newly read array.
C Program:
#include <stdio.h>
#include <stdlib.h>
struct Student {
int roll_no;
char name[50];
float gpa;
};
int main() {
int n, i;
printf("Enter the number of students: ");
scanf("%d", &n);
struct Student students[n]; // Array of structures
// Input student details
for (i = 0; i < n; i++) {
printf("\nEnter details for student %d:\n", i + 1);
printf("Roll No: ");
scanf("%d", &students[i].roll_no);
printf("Name: ");
scanf("%s", students[i].name);
printf("GPA: ");
scanf("%f", &students[i].gpa);
}
// --- Writing to the text file ---
FILE *fp;
fp= fopen("students.txt", "w"); // "w" for write text
if (fp== NULL) {
printf("Error opening file for writing!\n");
Computer Department-KMC, Bagbazar
return 1;
}
printf("\nSuccessfully wrote %d student records to students.txt\n", n);
for (i = 0; i < n; i++) {
fprintf(fp, "%d %s %.2f\n", students[i].roll_no, students[i].name,
students[i].gpa);
}
fclose(fp);
// --- Reading from the text file ---
fp= fopen("students.txt", "r"); // "r" for read text
if (fp== NULL) {
printf("Error opening file for reading!\n");
return 1;
}
struct Student read_students[n]; // Array to store the read data
printf("\n--- Student Details Read from Text File ---\n");
for (i = 0; i < n; i++) {
fscanf(fp, "%d %s %f", &read_students[i].roll_no,
read_students[i].name, &read_students[i].gpa);
printf("Student %d:\n", i + 1);
printf("Roll No: %d\n", read_students[i].roll_no);
printf("Name: %s\n", read_students[i].name);
printf("GPA: %.2f\n", read_students[i].gpa);
printf("\n");
}
fclose(fp);
return 0;
}
Output (example):
Enter the number of students: 2
Enter details for student 1:
Roll No: 101
Name: Jenish
GPA: 3.5
Enter details for student 2:
Roll No: 102
Name: Jamuna
GPA: 3.9
Successfully wrote 2 student records to students.txt
--- Student Details Read from Text File ---
Student 1:
Roll No: 101
Name: Jenish
GPA: 3.50
Computer Department-KMC, Bagbazar
Student 2:
Roll No: 102
Name: Jamuna
GPA: 3.90
Problem 6: Structure and File I/O (fwrite, fread)
Write a C program to define a Student structure with roll_number, name, and marks. The
program should:
1. Ask the user for the number of students (N).
2. Input details for N students into an array of structures.
3. Write the entire array of structures to a binary file named students.txt using fwrite().
4. Read the data back into a new array of structures using fread().
5. Display the details of all students from the newly read array.
C Program:
#include <stdio.h>
// Define the Student structure
struct Student {
char name[50];
int roll_number;
float marks;
};
int main() {
FILE *fptr;
int i,n;
printf("Enter the Number of students\n");
scanf("%d",&n);
struct Student students[n]; // Array of two student structures
// --- Writing data to file ---
// Open file in binary write mode ("wb")
fptr = fopen("students.txt", "wb");
if (fptr == NULL) {
printf("Error opening file for writing!\n");
return 1;
}
for(i=0; i<n;i++){
printf("Enter details for Student %d:\n",i+1);
printf("Name: ");
scanf(" %[^\n]", students[i].name);
printf("Roll Number: ");
scanf("%d", &students[i].roll_number);
printf("Marks: ");
scanf("%f", &students[i].marks);
}
Computer Department-KMC, Bagbazar
// Write the array of structures to the file
// fwrite(&address_of_data, size_of_each_element, number_of_elements,
file_pointer)
fwrite(students, sizeof(struct Student), n, fptr);
printf("\nStudent data written to students.dat successfully.\n");
// Close the file
fclose(fptr);
// --- Reading data from file ---
// Open file in binary read mode ("rb")
fptr = fopen("students.txt", "rb");
if (fptr == NULL) {
printf("Error opening file for reading!\n");
return 1;
}
// Read the array of structures from the file
// fread(&address_of_data, size_of_each_element, number_of_elements,
file_pointer)
fread(students, sizeof(struct Student), n, fptr);
printf("\nReading student data from students.txt:\n");
for (i = 0; i < n; i++) {
printf("Student %d:\n", i + 1);
printf("Name: %s\n", students[i].name);
printf("Roll Number: %d\n", students[i].roll_number);
printf("Marks: %.2f\n", students[i].marks);
printf("---------\n");
}
// Close the file
fclose(fptr);
return 0;
}
Output (example):
Enter the Number of students
3
Enter details for Student 1:
Name: rahul raja
Roll Number: 1
Marks: 33
Enter details for Student 2:
Name: raja ram
Roll Number: 2
Marks: 44
Enter details for Student 3:
Name: ram raja
Roll Number: 55
Marks: 33
Student data written to students.dat successfully.
Computer Department-KMC, Bagbazar
Reading student data from students.txt:
Student 1:
Name: rahul raja
Roll Number: 1
Marks: 33.00
---------
Student 2:
Name: raja ram
Roll Number: 2
Marks: 44.00
---------
Student 3:
Name: ram raja
Roll Number: 55
Marks: 33.00
Conclusion
By completing these exercises, I have gained a solid understanding of C file handling. I have
learned how to use various file I/O functions to work with character, integer, and formatted data,
as well as how to perform efficient block-level I/O for complex data types like structures
Computer Department-KMC, Bagbazar