Lab 10: File handling in C

Lab Report Information
Lab No.: 10
Title: File handling in C
Course: Computer Programming (CT 101), I Year I Part
Credit: Important Notes
C Programming Lab Report: Theory for Lab 10
File handling in C
This C Programming Lab Report explores File handling in C, the process of storing program data persistently in files. This allows data to be saved after the program ends.
Key Concepts and Functions:
- File Pointer (
FILE *fp;
): A pointer to a `FILE` structure, used to manage all file operations. fopen()
: Opens a file in a specific mode (e.g., “r” for read, “w” for write, “a” for append, “rb” for read binary). Returns `NULL` on failure.- Reading/Writing: Functions like `fprintf()`/`fscanf()` for text files, and `fwrite()`/`fread()` for binary files are used to transfer data.
fclose()
: Closes the file, saves data from buffers, and releases system resources.- Error Handling: Always check if `fopen()` returns `NULL` to ensure the file was opened successfully.
C Programming Lab Report: Programs for Lab 10
1. Student Record Management
Question:
Write a program to open a new file, read student records (name, roll, address, DOB) until the user says “no”, write the data to the file, and then display the file’s content.
Program Code:
#include <stdio.h> #include <stdlib.h> int main() { FILE *fp; char name[50], address[50], dob[20], choice; int roll; fp = fopen("student.txt", "w"); if (fp == NULL) { printf("Error opening file!"); exit(1); } do { printf("Enter name: "); scanf(" %[^\n]", name); printf("Enter roll number: "); scanf("%d", &roll); printf("Enter address: "); scanf(" %[^\n]", address); printf("Enter DOB (dd/mm/yyyy): "); scanf(" %[^\n]", dob); fprintf(fp, "Name: %s\nRoll: %d\nAddress: %s\nDOB: %s\n\n", name, roll, address, dob); printf("Add another record? (y/n): "); scanf(" %c", &choice); } while (choice == 'y' || choice == 'Y'); fclose(fp); printf("\n--- Reading data from file ---\n"); fp = fopen("student.txt", "r"); if (fp == NULL) { printf("Error opening file for reading!"); exit(1); } char ch; while ((ch = fgetc(fp)) != EOF) { putchar(ch); } fclose(fp); return 0; }
Output:
Enter name: Ram Enter roll number: 1 Enter address: Kathmandu Enter DOB (dd/mm/yyyy): 12/05/2002 Add another record? (y/n): y Enter name: Shyam Enter roll number: 2 Enter address: Pokhara Enter DOB (dd/mm/yyyy): 10/08/2001 Add another record? (y/n): n --- Reading data from file --- Name: Ram Roll: 1 Address: Kathmandu DOB: 12/05/2002 Name: Shyam Roll: 2 Address: Pokhara DOB: 10/08/2001
Algorithm:
- Start
- Open “student.txt” in write mode.
- Use a `do-while` loop to read student details.
- Inside the loop, write the details to the file using `fprintf()`.
- Ask the user to continue; repeat if ‘y’.
- Close the file.
- Reopen the file in read mode.
- Read the file character by character using `fgetc()` and print to the screen until `EOF`.
- Close the file.
- Stop.
2. Separate Even and Odd Numbers into Files
Question:
A file named `data.txt` contains integers. Read these numbers and store even numbers in `even.txt` and odd numbers in `odd.txt`.
Program Code:
#include <stdio.h> #include <stdlib.h> int main() { FILE *f_data, *f_even, *f_odd; int num; f_data = fopen("data.txt", "w"); fprintf(f_data, "11 22 33 44 55 66 77 88 99"); fclose(f_data); f_data = fopen("data.txt", "r"); f_even = fopen("even.txt", "w"); f_odd = fopen("odd.txt", "w"); if (f_data == NULL || f_even == NULL || f_odd == NULL) { printf("Error opening files!"); exit(1); } while (fscanf(f_data, "%d", &num) != EOF) { if (num % 2 == 0) { fprintf(f_even, "%d\n", num); } else { fprintf(f_odd, "%d\n", num); } } fclose(f_data); fclose(f_even); fclose(f_odd); printf("Files written successfully.\n"); return 0; }
Output:
Content of even.txt:
22
44
66
88
Content of odd.txt:
11
33
55
77
99
Algorithm:
- Start
- Open `data.txt` for reading, `even.txt` for writing, and `odd.txt` for writing.
- Check for file opening errors.
- Read integers from `data.txt` in a loop using `fscanf()`.
- If a number is even, write it to `even.txt`.
- If it’s odd, write it to `odd.txt`.
- Close all three files.
- Stop.
3. Copy File Contents
Question:
Write a program to copy the contents of one file to another.
Program Code:
#include <stdio.h> #include <stdlib.h> int main() { FILE *source_file, *dest_file; char ch; source_file = fopen("source.txt", "w"); fprintf(source_file, "This is a test file.\nIt has multiple lines.\n"); fclose(source_file); source_file = fopen("source.txt", "r"); dest_file = fopen("destination.txt", "w"); if (source_file == NULL || dest_file == NULL) { printf("Error opening files!"); exit(1); } while ((ch = fgetc(source_file)) != EOF) { fputc(ch, dest_file); } printf("File copied successfully.\n"); fclose(source_file); fclose(dest_file); return 0; }
Output:
Content of destination.txt:
This is a test file.
It has multiple lines.
Algorithm:
- Start
- Open a source file for reading and a destination file for writing.
- Check for file opening errors.
- Read from the source file character by character using `fgetc()` in a loop.
- Write each character to the destination file using `fputc()`.
- Continue until the end of the source file is reached (`EOF`).
- Close both files.
- Stop.
4. Count Characters, Words, and Lines in a File
Question:
Write a program to count the number of characters, words, and lines in a file.
Program Code:
#include <stdio.h> #include <stdlib.h> int main() { FILE *fp; char ch; int characters = 0, words = 0, lines = 0; fp = fopen("textfile.txt", "w"); fprintf(fp, "Hello world.\nThis is a C program.\n"); fclose(fp); fp = fopen("textfile.txt", "r"); if (fp == NULL) { printf("Error opening file!"); exit(1); } while ((ch = fgetc(fp)) != EOF) { characters++; if (ch == '\n') { lines++; words++; } else if (ch == ' ' || ch == '\t') { words++; } } // Increment lines and words for the last line/word if file is not empty if (characters > 0) { words++; lines++; } fclose(fp); printf("Total characters = %d\n", characters); printf("Total words = %d\n", words); printf("Total lines = %d\n", lines); return 0; }
Output:
Total words = 8
Total lines = 2
Algorithm:
- Start
- Initialize `characters`, `words`, and `lines` counters to 0.
- Open a file for reading.
- Read the file character by character until `EOF`.
- For each character, increment `characters`.
- If the character is a newline `\n`, increment `lines`.
- If the character is a space, tab, or newline, increment `words`.
- Adjust counts if necessary (e.g., for files without a final newline).
- Close the file and print the counts.
- Stop.
5. Billing System using Binary Files
Question:
Write a program to prepare a customer bill. Read item code, description, rate, and quantity, and store the data in a binary file. Finally, read all records, display them, and calculate the total amount.
Program Code:
#include <stdio.h> #include <string.h> #include <stdlib.h> struct bill { char item_code[10]; char des[50]; float rate, cost; int quantity; }; int main() { struct bill b; FILE *fp; char choice; float total_cost = 0; fp = fopen("record.bin", "wb"); if (fp == NULL) exit(1); do { // ... (Read item details) ... b.cost = b.rate * b.quantity; fwrite(&b, sizeof(struct bill), 1, fp); printf("Any more? (y/n): "); scanf(" %c", &choice); } while (choice == 'y' || choice == 'Y'); fclose(fp); fp = fopen("record.bin", "rb"); if (fp == NULL) exit(1); printf("\n%-10s %-20s %-10s %-10s %-10s\n", "Item Code", "Description", "Rate", "Quantity", "Cost"); printf("-----------------------------------------------------------\n"); while (fread(&b, sizeof(struct bill), 1, fp) == 1) { printf("%-10s %-20s %-10.2f %-10d %-10.2f\n", b.item_code, b.des, b.rate, b.quantity, b.cost); total_cost += b.cost; } fclose(fp); printf("-----------------------------------------------------------\n"); printf("Total Cost = %.2f\n", total_cost); return 0; }
Output:
Item Code Description Rate Quantity Cost ----------------------------------------------------------- 00227 Computer 22000.00 5 110000.00 007M Cell-phone 8000.00 10 80000.00 ----------------------------------------------------------- Total Cost = 190000.00
Algorithm:
- Start
- Define a `bill` structure.
- Open a binary file in write-binary mode (“wb”).
- In a `do-while` loop, get item details, calculate cost, and write the structure to the file using `fwrite()`.
- Close the file.
- Reopen in read-binary mode (“rb”).
- Read records one by one using `fread()` in a loop.
- Inside the loop, print the record details and add its cost to `total_cost`.
- After the loop, print the final `total_cost`.
- Stop.
Discussion and Conclusion
This C Programming Lab Report on File handling in C provided a thorough introduction to creating applications with persistent data storage. The exercises covered fundamental operations for both text and binary files. We learned to manage different file modes and the importance of robust error checking. The transition from text-based I/O (`fprintf`) to binary I/O (`fwrite`/`fread`) demonstrated the efficiency of using binary files for storing structures. In conclusion, this lab successfully imparted the essential skills needed to manipulate files in C, enabling the development of more powerful programs.