📁
File Operations
🏠 Home Lecture 23: File Ops
The Real World Scenario 🌎

Processing Big Data

Imagine your professor gives you a CSV File (Comma Separated Values) containing the exam marks of 1,000 students. You need to calculate the average and assign a Grade for each. How do you do it?

💡 Automation with C

Would you open the Excel file and type 1000 formulas manually?
Yes, it builds character.
No! I will write a C Program to Read & Write!
students.csvThe Input File
RollNo,Name,Marks 101,Abhay,85 102,Rahul,45 103,Priya,92 ... (997 more rows)
Level 1: Characters

Character I/O and EOF

The most basic way to read a file is character-by-character using fgetc(). We keep reading until we hit a special marker called EOF (End Of File).

read_chars.cHover to explore ✶
FILE *ptr = fopen("story.txt", "r"); char ch; // Read character by character until EOF while ((ch = fgetc(ptr)) != EOF) { printf("%c", ch); } fclose(ptr);
🔎 The Magic of fgetc()

When you call fgetc(), it reads a character and automatically moves the cursor to the next character. You don't need a counter!
Write counterpart: fputc('A', ptr); writes a single character to the file.
Application 1

Building a Text Analyzer (Word Count)

Let's use our fgetc() logic to count total characters, words, and lines in a file. This is exactly how tools like MS Word count your essay!

word_count.cApplication Code
FILE *file = fopen("essay.txt", "r"); int chars = 0, words = 0, lines = 0; char ch; while ((ch = fgetc(file)) != EOF) { chars++; // Every keystroke is a char if (ch == ' ' || ch == '\n') { words++; } if (ch == '\n') { lines++; } } fclose(file); printf("Words: %d, Lines: %d", words, lines);

Input: essay.txt

Hello world! This is C programming. File handling is fun.

Output

Chars: 56 Words: 9 Lines: 3
Application 2

Formatted I/O: CSV Grade Calculator

Character-by-character is too slow for formatted data. We use fscanf() to read formatted variables (Strings, Ints, Floats) directly, and fprintf() to write!

csv_processor.cHover to explore ✶
FILE *in = fopen("marks.txt", "r"); FILE *out = fopen("grades.txt", "w"); char name[50]; int marks; // Read Name and Marks. Returns EOF when file ends. while (fscanf(in, "%s %d", name, &marks) != EOF) { char grade = (marks >= 40) ? 'P' : 'F'; // Write Name, Marks, and calculated Grade fprintf(out, "%s %d %c\n", name, marks, grade); } fclose(in); fclose(out);

marks.txt (Input)

Abhay 85 Rahul 35 Priya 92

grades.txt (Output generated)

Abhay 85 P Rahul 35 F Priya 92 P
Knowledge Check ✍

Let's test what you've learned!

Question 1 of 3
Loading...