Chapter 6: File Operations in C – Detailed Explanation
File handling in C allows a program to store and retrieve data permanently from secondary
storage (hard disks, SSDs). Unlike variables that are temporary and lost when a program
ends, files provide persistent storage, essential for real-world applications like databases,
logs, or configuration files.
---
1. Introduction to File Operations
Files are sequences of data stored in secondary memory.
Uses of files:
Storing large amounts of data that cannot fit in memory
Sharing data between programs
Maintaining data permanently across program executions
Types of files in C:
1. Text files – Human-readable, stored as lines of characters.
2. Binary files – Stored in exact byte format of memory data; faster and more compact.
Reference: Thareja (2021), Balagurusamy (2019), Kanetkar (2020)
---
2. File Handling Functions in C
C provides several standard functions in <stdio.h> for file operations:
Function Purpose
fopen()Opens a file
fclose()Closes a file
fgetc() Reads a character from a file
fgets() Reads a string/line from a file
fputc() Writes a character to a file
fputs() Writes a string to a file
fprintf() Writes formatted text
fread() Reads binary data
fwrite() Writes binary data
fseek() Moves the file pointer to a position
ftell() Returns the current position of the pointer
rewind() Moves the pointer to the beginning of the file
feof() Checks end-of-file
ferror() Checks file error
---
3. Opening a File
A file must be opened before any operation. Use fopen() which returns a file pointer of type
FILE*.
Syntax:
FILE *fopen(const char *filename, const char *mode);
Modes:
Mode Purpose
"r" Read text file
"w" Write text file (creates new or overwrite)
"a" Append text file
"rb" Read binary file
"wb" Write binary file
"ab" Append binary file
"r+" Read/write text file
"rb+" Read/write binary file
Example:
FILE *fp = fopen("example.txt", "r");
if (fp == NULL) {
perror("Error opening file");
} else {
printf("File opened successfully.\n");
Notes:
Always check if fopen() returns NULL.
Binary files use modes ending with b.
---
4. Closing a File
After finishing file operations, close the file using fclose():
fclose(fp);
Why close a file?
Ensures all data in buffers is written to disk
Frees system resources
Prevents data corruption
Reference: Kalicharan (2022), Forouzan & Afyouni (2023)
---
5. Reading from a File
5.1 Text File Reading
Character by character: fgetc()
char ch;
while ((ch = fgetc(fp)) != EOF) {
putchar(ch);
Line by line: fgets()
char line[100];
fgets(line, 100, fp);
Formatted reading: fscanf()
int num;
fscanf(fp, "%d", &num);
5.2 Binary File Reading
Binary files store data in the exact memory format.
fread() reads binary data into memory:
fread(&buffer, sizeof(data_type), count, fp);
Example:
int num;
FILE *fp = fopen("data.bin", "rb");
fread(&num, sizeof(int), 1, fp);
Note: Binary files preserve exact data structure; useful for numbers, structs, or large
datasets.
---
6. Writing to a File
6.1 Text File Writing
Character: fputc()
String: fputs()
Formatted text: fprintf()
FILE *fp = fopen("output.txt", "w");
fputs("Hello C Programming!\n", fp);
fprintf(fp, "Number: %d\n", 123);
fclose(fp);
6.2 Binary File Writing
Use fwrite() to write data:
int num = 1234;
fwrite(&num, sizeof(int), 1, fp);
Notes:
Binary writing is faster and stores exact bytes.
Always match reading and writing data types in binary files.
---
7. File Pointers
A file pointer keeps track of:
The current position in the file
Whether the file is open
Buffer status
7.1 Moving the File Pointer
fseek(fp, offset, origin) – Move pointer
SEEK_SET – Start
SEEK_CUR – Current position
SEEK_END – End of file
ftell(fp) – Returns current position
rewind(fp) – Moves to beginning
Example:
fseek(fp, 0, SEEK_END);
long size = ftell(fp);
rewind(fp);
Reference: Thareja (2021), Kanetkar (2020)
---
8. Binary vs Text Files
Feature Text File Binary File
Content Human-readable Raw bytes
StorageLarger Compact
Functions fgetc, fgets, fputs, fprintf fread, fwrite
Speed Slower Faster
Flexibility Easy to edit Cannot edit manually
---
9. Error Handling in File Operations
Errors can occur due to:
File does not exist
No permission to read/write
Disk full
Methods:
1. Check if fopen() returns NULL
if (fp == NULL) perror("File error");
2. Detect end-of-file: feof(fp)
3. Check read/write errors: ferror(fp)
Example:
if (ferror(fp)) {
printf("Error during file operation.\n");
---
10. Practical Programs
Program 1 – Text File Reading
#include <stdio.h>
int main() {
FILE *fp = fopen("sample.txt", "r");
char ch;
if (!fp) { perror("Error"); return 1; }
while ((ch = fgetc(fp)) != EOF) putchar(ch);
fclose(fp);
return 0;
Program 2 – Writing Data to Text File
#include <stdio.h>
int main() {
FILE *fp = fopen("output.txt", "w");
if (!fp) { perror("Error"); return 1; }
fputs("Welcome to C File Handling!\n", fp);
fclose(fp);
return 0;
Program 3 – Binary File Write & Read
#include <stdio.h>
int main() {
FILE *fp;
int num = 12345, readNum;
fp = fopen("data.bin", "wb");
fwrite(&num, sizeof(int), 1, fp);
fclose(fp);
fp = fopen("data.bin", "rb");
fread(&readNum, sizeof(int), 1, fp);
printf("Number read: %d\n", readNum);
fclose(fp);
return 0;
}
---
11. Summary
File handling is essential for persistent storage.
Text files: human-readable, slower.
Binary files: fast, exact data, compact.
Always open and close files properly.
File pointers allow random access.
Use error handling to prevent crashes.
Master reading, writing, and manipulating both text and binary files for robust
programming.
---
Chapter 7: Standard Libraries and Header Files in C Programming
---
1. Introduction
In C programming, header files are files containing function declarations, macro definitions,
constants, and data types. Header files allow the programmer to modularize code and reuse
functionalities across multiple programs.
Header files are classified into:
1. Standard Header Files – provided by C for common operations.
2. User-Defined Header Files – created by programmers to encapsulate reusable code.
Using header files improves readability, maintainability, and reduces redundancy in
programs.
---
2. Standard Library Header Files
C comes with a set of pre-defined standard libraries, each having specialized functions.
Some commonly used libraries are:
stdio.h – Standard input/output functions.
stdlib.h – General utility functions.
string.h – String manipulation functions.
math.h – Mathematical functions.
---
2.1 stdio.h (Standard Input/Output Library)
Functions provided by stdio.h include:
Function Description
printf()Prints formatted data to the console.
scanf() Reads formatted input from the user.
getchar() Reads a single character.
putchar() Prints a single character.
fgets() Reads a string from input.
fputs() Prints a string.
Example:
#include <stdio.h>
int main() {
char name[50];
int age;
printf("Enter your name: ");
fgets(name, sizeof(name), stdin);
printf("Enter your age: ");
scanf("%d", &age);
printf("Hello %sYou are %d years old.\n", name, age);
return 0;
---
2.2 stdlib.h (Standard Library)
Functions in stdlib.h include:
Function Description
malloc() Allocates memory dynamically.
calloc()Allocates zero-initialized memory.
free() Deallocates memory.
exit() Terminates a program.
atoi(), atof() Convert strings to integers/floats.
rand() Generates random numbers.
Example:
#include <stdio.h>
#include <stdlib.h>
int main() {
int *ptr = (int *)malloc(sizeof(int));
if(ptr == NULL) {
printf("Memory allocation failed!\n");
exit(1);
*ptr = 42;
printf("Value = %d\n", *ptr);
free(ptr);
return 0;
---
2.3 string.h (String Handling Library)
Functions include:
Function Description
strlen()Returns the length of a string.
strcpy() Copies one string to another.
strcat()Concatenates strings.
strcmp() Compares two strings.
strstr() Finds substring in a string.
Example:
#include <stdio.h>
#include <string.h>
int main() {
char str1[50] = "Hello, ";
char str2[] = "World!";
strcat(str1, str2);
printf("Concatenated string: %s\n", str1);
printf("Length: %lu\n", strlen(str1));
return 0;
---
2.4 math.h (Mathematical Functions)
Common functions include:
Function Description
sqrt(x) Square root of x.
pow(x,y) x raised to power y.
sin(x) Sine function.
cos(x) Cosine function.
tan(x) Tangent function.
fabs(x) Absolute value of x.
Example:
#include <stdio.h>
#include <math.h>
int main() {
double num = 16.0;
printf("Square root = %.2f\n", sqrt(num));
printf("2^3 = %.2f\n", pow(2,3));
return 0;
---
3. User-Defined Header Files
User-defined header files allow programmers to create custom functions, macros, and data
types for reuse.
3.1 Creating a Header File
math_operations.h
#ifndef MATH_OPERATIONS_H
#define MATH_OPERATIONS_H
int add(int a, int b);
int subtract(int a, int b);
int multiply(int a, int b);
float divide(int a, int b);
#endif
3.2 Implementing Functions
math_operations.c
#include "math_operations.h"
int add(int a, int b) { return a + b; }
int subtract(int a, int b) { return a - b; }
int multiply(int a, int b) { return a * b; }
float divide(int a, int b) { return (float)a/b; }
3.3 Using User-Defined Header File
#include <stdio.h>
#include "math_operations.h"
int main() {
int x=10, y=5;
printf("Add: %d\n", add(x,y));
printf("Subtract: %d\n", subtract(x,y));
printf("Multiply: %d\n", multiply(x,y));
printf("Divide: %.2f\n", divide(x,y));
return 0;
---
4. Practical Programs Using Standard and User-Defined Libraries
4.1 Program 1: Calculator
Uses user-defined math library.
Performs addition, subtraction, multiplication, division.
4.2 Program 2: Student Record System
Uses stdio.h and string.h.
Stores, displays, and searches student records.
4.3 Program 3: Banking System
Uses stdlib.h for dynamic memory.
Deposit, withdraw, and balance operations.
---
5. Projects
5.1 Project 1: Library Management System
Features:
Add, delete, search books.
Track issued books.
Save data using file handling.
5.2 Project 2: Inventory Management System
Features:
Add, update, and delete product records.
Generate stock and sales reports.
Utilize user-defined header functions for calculations.
---
6. Summary
Header files are reusable code units.
Standard libraries provide ready-made functions.
User-defined libraries allow modular programming.
Practical applications include calculators, record systems, and management software.
Projects demonstrate full-scale usage of libraries and header files.
---
3. Adding step-by-step explanations for practical programs.
4. Adding full projects with code, input/output, and explanations.
---
Section 1: Practicals
Practical 1 – Calculator using User-Defined Library
Algorithm:
1. Start
2. Input two numbers
3. Display operation menu: Add, Subtract, Multiply, Divide
4. Take user choice
5. Perform operation using functions from user-defined library
6. Display result
7. End
Code:
math_operations.h
#ifndef MATH_OPERATIONS_H
#define MATH_OPERATIONS_H
int add(int a, int b);
int subtract(int a, int b);
int multiply(int a, int b);
float divide(int a, int b);
#endif
math_operations.c
#include "math_operations.h"
int add(int a,int b){ return a+b; }
int subtract(int a,int b){ return a-b; }
int multiply(int a,int b){ return a*b; }
float divide(int a,int b){ return (float)a/b; }
main.c
#include <stdio.h>
#include "math_operations.h"
int main() {
int x,y,choice;
printf("Enter first number: "); scanf("%d",&x);
printf("Enter second number: "); scanf("%d",&y);
printf("1.Add 2.Subtract 3.Multiply 4.Divide\nChoose operation: ");
scanf("%d",&choice);
switch(choice){
case 1: printf("Sum = %d\n", add(x,y)); break;
case 2: printf("Difference = %d\n", subtract(x,y)); break;
case 3: printf("Product = %d\n", multiply(x,y)); break;
case 4: printf("Quotient = %.2f\n", divide(x,y)); break;
default: printf("Invalid choice!\n");
return 0;
Sample Output:
Enter first number: 10
Enter second number: 5
Choose operation: 4
Quotient = 2.00
---
Practical 2 – Student Record Management System
Algorithm:
1. Start
2. Input number of students
3. Create array of structures Student
4. Input name, roll, marks for each student
5. Display all student records
6. End
Code:
#include <stdio.h>
struct Student {
char name[50];
int roll;
float marks;
};
int main() {
int n;
printf("Enter number of students: "); scanf("%d",&n);
struct Student s[n];
for(int i=0;i<n;i++){
printf("Enter name: "); scanf(" %[^\n]", s[i].name);
printf("Enter roll: "); scanf("%d",&s[i].roll);
printf("Enter marks: "); scanf("%f",&s[i].marks);
printf("\nStudent Records:\n");
for(int i=0;i<n;i++)
printf("Name: %s, Roll: %d, Marks: %.2f\n", s[i].name, s[i].roll, s[i].marks);
return 0;
Sample Output:
Enter number of students: 2
Enter name: Alice
Enter roll: 101
Enter marks: 89.5
Enter name: Bob
Enter roll: 102
Enter marks: 92.0
Student Records:
Name: Alice, Roll: 101, Marks: 89.50
Name: Bob, Roll: 102, Marks: 92.00
---
Practical 3 – Banking System
Algorithm:
1. Start
2. Input account name and number
3. Initialize balance = 0
4. Display menu: Deposit, Withdraw, Display, Exit
5. Perform chosen operation
6. Repeat until exit
7. End
Code:
#include <stdio.h>
struct Account {
char name[50];
int acc_no;
float balance;
};
void deposit(struct Account *a,float amt){ a->balance+=amt; printf("Amount deposited
successfully.\n"); }
void withdraw(struct Account *a,float amt){ if(amt>a->balance) printf("Insufficient
balance!\n"); else { a->balance-=amt; printf("Amount withdrawn successfully.\n"); } }
void display(struct Account a){ printf("Name: %s, Account No: %d, Balance: %.2f\n",
a.name, a.acc_no, a.balance); }
int main() {
struct Account acc;
printf("Enter account name: "); scanf(" %[^\n]", acc.name);
printf("Enter account number: "); scanf("%d",&acc.acc_no);
acc.balance=0;
int choice; float amount;
do {
printf("\n1.Deposit 2.Withdraw 3.Display 4.Exit\nChoose option: ");
scanf("%d",&choice);
switch(choice){
case 1: printf("Enter amount to deposit: "); scanf("%f",&amount);
deposit(&acc,amount); break;
case 2: printf("Enter amount to withdraw: "); scanf("%f",&amount);
withdraw(&acc,amount); break;
case 3: display(acc); break;
case 4: printf("Exiting Banking System...\n"); break;
default: printf("Invalid option!\n");
}
} while(choice!=4);
return 0;
Sample Output:
Deposit 1000 → Amount deposited successfully
Withdraw 500 → Amount withdrawn successfully
Display → Name: John Doe, Account No: 12345, Balance: 500.00
---
Section 2: Projects
---
Project 1 – Library Management System
Algorithm:
1. Start
2. Declare Book structure
3. Functions: addBook, issueBook, returnBook, displayBook
4. Initialize books
5. Display books
6. Issue/Return books based on user input
7. Repeat until exit
8. End
Code:
#include <stdio.h>
#include <string.h>
struct Book { int id; char title[50]; char author[50]; int available; };
void addBook(struct Book *b,int id,char *title,char *author){ b->id=id; strcpy(b->title,title);
strcpy(b->author,author); b->available=1; }
void issueBook(struct Book *b){ if(b->available){ b->available=0; printf("Book issued
successfully.\n"); } else printf("Book not available.\n"); }
void returnBook(struct Book *b){ b->available=1; printf("Book returned successfully.\n"); }
void displayBook(struct Book b){ printf("ID:%d, Title:%s, Author:%s, %s\
n",b.id,b.title,b.author,b.available?"Available":"Issued"); }
int main() {
struct Book b1,b2;
addBook(&b1,1,"C Programming","K&R");
addBook(&b2,2,"Let Us C","Kanetkar");
int choice,id;
do {
printf("\n1.Display 2.Issue 3.Return 4.Exit\nEnter choice: "); scanf("%d",&choice);
switch(choice){
case 1: displayBook(b1); displayBook(b2); break;
case 2: printf("Enter Book ID to issue: "); scanf("%d",&id);
if(id==b1.id) issueBook(&b1); else if(id==b2.id) issueBook(&b2); else
printf("Invalid ID!\n"); break;
case 3: printf("Enter Book ID to return: "); scanf("%d",&id);
if(id==b1.id) returnBook(&b1); else if(id==b2.id) returnBook(&b2); else
printf("Invalid ID!\n"); break;
case 4: printf("Exiting Library System...\n"); break;
default: printf("Invalid choice!\n");
} while(choice!=4);
return 0;
Sample Output:
Display → ID:1, Title:C Programming, Author:K&R, Available
Issue ID 1 → Book issued successfully
Display → ID:1, Title:C Programming, Author:K&R, Issued
Return ID 1 → Book returned successfully
Display → ID:1, Title:C Programming, Author:K&R, Available
---
Project 2 – Inventory Management System
Algorithm:
1. Start
2. Declare Product structure
3. Functions: addProduct, displayProduct, updateStock
4. Initialize products
5. Display products
6. Update stock based on user input
7. Repeat until exit
8. End
Code:
#include <stdio.h>
#include <string.h>
struct Product { int id; char name[50]; int quantity; float price; };
void addProduct(struct Product *p,int id,char *name,int qty,float price){ p->id=id; strcpy(p-
>name,name); p->quantity=qty; p->price=price; }
void displayProduct(struct Product p){ printf("ID:%d, Name:%s, Quantity:%d, Price:%.2f\
n",p.id,p.name,p.quantity,p.price); }
void updateStock(struct Product *p,int qty){ p->quantity+=qty; printf("Stock updated. New
quantity: %d\n",p->quantity); }
int main() {
struct Product p1;
addProduct(&p1,101,"Laptop",10,50000.0);
int choice,qty;
do {
printf("\n1.Display 2.Update Stock 3.Exit\nEnter choice: "); scanf("%d",&choice);
switch(choice){
case 1: displayProduct(p1); break;
case 2: printf("Enter quantity to add (negative to reduce): "); scanf("%d",&qty);
updateStock(&p1,qty); break;
case 3: printf("Exiting Inventory System...\n"); break;
default: printf("Invalid choice!\n");
} while(choice!=3);
return 0;
}
Sample Output:
Display → ID:101, Name:Laptop, Quantity:10, Price:50000.00
Update +5 → Stock updated. New quantity: 15
Update -3 → Stock updated. New quantity: 12