PROGRAMMING FUNDAMENTAL’S LAB
ASSIGNMENT
FILE HANDLING:
File handling in C language refers to the process of creating, reading, writing, and
manipulating files on a storage device. It allows you to store data permanently on disk for
future use. Here's a brief overview of file handling concepts in C:
1. File Operations: Common file operations include:
o Creating a new file
o Opening an existing file
o Reading data from a file
o Writing data to a file
o Closing a file
2. File Pointer: To perform file operations, you need a file pointer. It is a pointer of
type FILE that keeps track of the current position in the file.
3. File Modes: When opening a file, you specify the mode in which you want to
access the file, such as:
o "r": Read mode (opens an existing file for reading)
o "w": Write mode (creates a new file or truncates an existing file for writing)
o "a": Append mode (opens a file for appending data)
o "r+": Read/Write mode (opens an existing file for both reading and writing)
o "w+": Read/Write mode (creates a new file or truncates an existing file for
both reading and writing)
o "a+": Read/Write mode (opens a file for both reading and writing, appending
data to the end)
4. File Handling Functions: Common functions used in file handling include:
o fopen(): Opens a file and returns a file pointer
o fclose(): Closes an opened file
o fgetc(): Reads a character from a file
o fputc(): Writes a character to a file
o fgets(): Reads a string from a file
o fputs(): Writes a string to a file
o fread(): Reads a block of data from a file
o fwrite(): Writes a block of data to a file
TASK
Storing student’s information using file handling.
#include <stdio.h>
#include <stdlib.h>
struct Student {
char name[50];
int rollNo;
float marks;
};
int main() {
struct Student student;
FILE *file;
file = fopen("student_data.txt", "w");
if (file == NULL) {
printf("Error opening file!\n");
exit(1);
}
printf("Enter student name: ");
fgets(student.name, sizeof(student.name), stdin);
printf("Enter roll number: ");
scanf("%d", &student.rollNo);
printf("Enter marks: ");
scanf("%f", &student.marks);
fprintf(file, "Name: %s", student.name);
fprintf(file, "Roll Number: %d\n", student.rollNo);
fprintf(file, "Marks: %.2f\n", student.marks);
fclose(file);
printf("Data written to file successfully.\n");
return 0;
}