C ProgrammingUnit 109 min read
File Handling in C: Operations, Modes, and Practical Applications
Unit 10 of C Programming covers file handling concepts, including file types, modes of opening files, standard file operations (read/write), error handling, and practical applications like data persistence in real-world systems. Learn with visual traces, code examples, and real-world ties to Nepalese apps like eSewa an
Key Concepts and Definitions
What is a File?
A file is a named collection of related data stored on secondary memory (e.g., hard disk, USB). Files allow programs to:
- Persist data beyond program execution.
- Share data between different programs.
- Store large amounts of data efficiently.
Types of Files in C
Files in C are categorized based on their content and access method:
- Text Files: Store data as characters (e.g.,
.txt,.csv). - Binary Files: Store data in binary format (e.g.,
.exe,.dat). - Sequential Access Files: Data is read/written in order (like a tape).
- Random Access Files: Data can be accessed directly by specifying a position (like a hard disk).
File Handling in C: Step-by-Step
1. File Pointers and FILE Structure
Every file in C is associated with a file pointer of type FILE*. This pointer holds information about the file, such as:
- File name.
- File mode (read/write).
- Current position in the file.
#include <stdio.h>
int main() {
FILE *fp; // Declare a file pointer
fp = fopen("example.txt", "r"); // Open file in read mode
if (fp == NULL) {
printf("Error opening file!\n");
return 1;
}
// File operations here...
fclose(fp); // Close the file
return 0;
}
2. Modes of Opening Files
Files can be opened in different modes, specified as the second argument to fopen():
| Mode | Description | Example Use Case |
|---|---|---|
"r" |
Open for reading (file must exist) | Reading a log file. |
"w" |
Open for writing (creates/truncates) | Writing a new report. |
"a" |
Open for appending (creates if needed) | Adding entries to a transaction log. |
"r+" |
Open for reading/writing | Editing a configuration file. |
"wb" |
Open binary file for writing | Saving an image file. |
In the Real World
eSewa (Nepal):
- Uses file handling to store transaction records (e.g., electricity bills, tax payments) in binary or text files. When you pay your bill, eSewa writes your payment details to a secure file for future reference and auditing.
- Example: When you check your transaction history, eSewa reads from these files to display your past payments.
Ncell (Nepal):
- Stores customer data (e.g., SIM registration details, call logs) in databases, which are essentially binary files managed by file-handling systems. When you recharge, Ncell updates your balance in a file linked to your SIM number.
- Example: If you call customer service, their system reads your account details from a file to verify your identity and balance.
Daraz (Nepal):
- Uses file handling to manage order queues. When you place an order, Daraz writes your order details to a file (or database) and processes it sequentially. During peak sales (e.g., Dashain), orders are read from files and fulfilled in a first-in-first-out (FIFO) manner, similar to a queue data structure.
- Example: If Daraz’s system crashes, it can recover unprocessed orders from a backup file to ensure no order is lost.
File Operations: Read and Write
Writing to a File
Use fprintf() or fputc() to write data to a file. Example:
FILE *fp = fopen("data.txt", "w");
if (fp == NULL) {
printf("Error opening file!\n");
return 1;
}
fprintf(fp, "Hello, File Handling!\n"); // Write a string
fputc('A', fp); // Write a single character
fclose(fp);
Trace of fprintf:
| Step | Action | File Content After Step |
|---|---|---|
| 1 | fopen("data.txt", "w") |
File is created (empty). |
| 2 | fprintf(fp, "Hello...") |
Hello, File Handling!\n |
| 3 | fputc('A', fp) |
Hello, File Handling!\nA |
Reading from a File
Use fscanf() or fgetc() to read data. Example:
FILE *fp = fopen("data.txt", "r");
if (fp == NULL) {
printf("Error opening file!\n");
return 1;
}
char ch;
while ((ch = fgetc(fp)) != EOF) { // Read until end of file
printf("%c", ch);
}
fclose(fp);
Trace of fgetc:
| Step | Action | Variable ch |
File Pointer Position |
|---|---|---|---|
| 1 | fgetc(fp) |
'H' | Start of file |
| 2 | fgetc(fp) |
'e' | After 'H' |
| 3 | fgetc(fp) |
'\n' | After 'e' |
| ... | ... | ... | ... |
| N | fgetc(fp) == EOF |
EOF | End of file |
Binary File Handling
Binary files store data in its original binary format (e.g., integers, floats). Use fread() and fwrite():
#include <stdio.h>
struct Student {
int roll;
char name[50];
};
int main() {
struct Student s1 = {101, "Ramesh"};
FILE *fp = fopen("students.dat", "wb"); // Open in binary write mode
fwrite(&s1, sizeof(struct Student), 1, fp); // Write struct to file
fclose(fp);
return 0;
}
Binary File Trace:
graph LR
A["Struct in Memory: s1"] -->|"sizeof"| B["Binary Data (e.g., 0x65 0x00 0x01 0x00...)"]
B -->|"fwrite"| C["File on Disk: students.dat"]
C -->|"fread"| D["Restored Struct in Memory"]Error Handling in File Operations
Always check if a file operation succeeds:
FILE *fp = fopen("nonexistent.txt", "r");
if (fp == NULL) {
perror("Error"); // Prints system error message
return 1;
}
// File operations...
fclose(fp);
Common Errors:
| Error Condition | Cause | Solution |
|---|---|---|
fp == NULL |
File not found or permission denied | Check file path/permissions. |
fprintf returns negative |
Disk full or write error | Free up space or check disk. |
fscanf fails |
Data format mismatch | Verify input format. |
Practical Example: Transaction Log for a Bank
Suppose a bank wants to log all transactions (deposit/withdrawal) for auditing. Here’s how file handling can be used:
#include <stdio.h>
#include <time.h>
struct Transaction {
int account_no;
char type[10]; // "Deposit" or "Withdrawal"
double amount;
time_t timestamp;
};
void logTransaction(int acc_no, char *type, double amount) {
FILE *fp = fopen("transactions.log", "a"); // Append mode
struct Transaction t = {acc_no, type, amount, time(NULL)};
fprintf(fp, "%d,%s,%.2f,%ld\n", t.account_no, t.type, t.amount, t.timestamp);
fclose(fp);
}
int main() {
logTransaction(1001, "Deposit", 5000.00);
logTransaction(1002, "Withdrawal", 2000.00);
return 0;
}
File After Logging:
1001,Deposit,5000.00,1634567890
1002,Withdrawal,2000.00,1634567891
Visualization of File Growth:
sequenceDiagram
participant BankApp as Bank Application
participant File as transactions.log
BankApp->>File: Append "1001,Deposit,5000.00,..."
BankApp->>File: Append "1002,Withdrawal,2000.00,..."
Note over File: File grows with each transactionComparison: Text vs. Binary Files
| Feature | Text Files | Binary Files |
|---|---|---|
| Storage Format | ASCII/Unicode characters | Raw bytes (e.g., 0x01 0x02) |
| Readability | Human-readable | Not human-readable |
| Speed | Slower (conversion overhead) | Faster (direct access) |
| Use Case | Logs, configuration files | Databases, images, executables |
| Example in Nepal | eSewa transaction logs | Ncell customer data records |
Advanced: Random Access Files
Random access allows reading/writing at specific positions using fseek():
FILE *fp = fopen("data.bin", "rb+");
int num = 100;
fseek(fp, 0, SEEK_SET); // Move to start of file
fwrite(&num, sizeof(int), 1, fp); // Write at position 0
fseek(fp, 4, SEEK_SET); // Move to position 4 (next int)
int new_num = 200;
fwrite(&new_num, sizeof(int), 1, fp);
fclose(fp);
Trace of fseek:
Exam Tip
- File Modes: Remember the difference between
"w"(truncate) and"a"(append). A common mistake is using"w"when you want to add data without losing existing content. - Error Handling: Always check
fopen()and file operation returns. In exams, assume files may not exist or may be corrupted. - Binary vs. Text: Know when to use each. Binary is faster but less portable; text is slower but human-readable.
- Practical Scenarios: Be ready to explain how file handling is used in real-world systems (e.g., logging in eSewa, order processing in Daraz).
- Code Traces: For questions involving file operations, trace the file content after each step (e.g., after
fprintforfread). - Common Functions: Memorize these:
fopen(),fclose(): Open/close files.fprintf(),fscanf(): Formatted I/O.fputc(),fgetc(): Character I/O.fread(),fwrite(): Binary I/O.fseek(),ftell(): Random access.
Based on the TU BIM syllabus for C Programming (IT232), unit 10.
Discussion
Loading…