C Programming Day 11
Introduction
Welcome to Day 11 of the C Programming Full Course.
In the previous lesson, you learned about Structures and Unions in C. You learned how to organize related information using structures, work with arrays of structures, create nested structures, use structure pointers, and understand how unions share memory.
Until now, most of the programs you've written have stored data temporarily in variables, arrays, or structures.
But what happens when the program ends?
The data stored in normal variables is lost.
For example:
int marks = 90;
When the program finishes, that value is no longer available to the next execution.
To permanently store information, we can use files.
C provides several functions for working with files, including:
fopen() fclose() fprintf() fscanf() fgetc() fputc() fgets() fputs()
In this lesson, you'll learn how to create, open, read, write, append, and close files in C.
What is File Handling in C?
File handling is the process of creating, opening, reading, writing, modifying, and closing files using a programming language.
In C, file handling is primarily performed using the FILE type and functions provided by the standard I/O library.
You need:
#include <stdio.h>
A typical file-handling program looks like this:
#include <stdio.h> int main() { FILE *file; file = fopen("data.txt", "w"); if(file == NULL) { printf("Unable to open file.\n"); return 1; } fprintf(file, "Hello, C Programming!"); fclose(file); return 0; }
This program:
-
Creates or opens
data.txt. - Writes text to it.
- Closes the file.
Why Do We Need Files?
Files allow programs to store information beyond the lifetime of a single execution.
For example, a student management system could store:
Student ID Student Name Marks Grade
A banking application could store:
Account Number Customer Name Balance Transaction History
An inventory application could store:
Product ID Product Name Price Quantity
Without files, this information would generally disappear when the program terminates.
Types of Files in C
C programs commonly work with two broad categories of files:
1. Text Files
Text files store information in a human-readable form.
Example:
student.txt products.txt employees.txt
A text file might contain:
101 Jitu 85.5 102 Rahim 90.0 103 Karim 78.5
2. Binary Files
Binary files store data as binary representations rather than ordinary human-readable text.
They are useful for storing structured data efficiently, but require appropriate binary I/O functions and careful consideration of portability and data representation.
In this lesson, we'll focus mainly on text-file handling.
What is a File Pointer?
In C, files are represented through a FILE object.
We normally work with a pointer to that object:
FILE *file;
Here:
-
FILEis a type declared by<stdio.h>. -
fileis a pointer used to refer to an opened stream.
Think of it as a handle that your program uses to communicate with the file.
Opening a File with fopen()
The fopen() function is used to open a file.
Syntax:
fopen("filename", "mode");
Example:
FILE *file; file = fopen("data.txt", "r");
Here:
data.txt → File name r → Opening mode
The function returns a FILE *.
Checking Whether a File Opened Successfully
Always check the return value of fopen().
#include <stdio.h> int main() { FILE *file; file = fopen("data.txt", "r"); if(file == NULL) { printf("File could not be opened.\n"); return 1; } printf("File opened successfully.\n"); fclose(file); return 0; }
If opening fails, fopen() returns NULL.
Possible reasons include:
- File does not exist in read mode.
- Permission is denied.
- The path is invalid.
- The storage location is unavailable.
File Opening Modes in C
The most common text modes are:
| Mode | Meaning |
|---|---|
r | Open for reading |
w | Open for writing |
a | Open for appending |
r+ | Open for reading and writing |
w+ | Open for reading and writing, truncating existing content |
a+ | Open for reading and appending |
Let's understand them one by one.
r Mode — Read
file = fopen("data.txt", "r");
The file must already exist.
If it doesn't exist, opening normally fails.
Use r when you want to read existing data.
w Mode — Write
file = fopen("data.txt", "w");
This mode is used for writing.
Important:
If the file already exists, opening it in
wmode generally truncates its previous contents.
If the file doesn't exist, a new file is generally created.
Therefore, be careful when using w.
a Mode — Append
file = fopen("data.txt", "a");
Append mode writes new data at the end of the file.
Existing content is preserved.
This is useful for:
- Logs
- Transaction histories
- Student records
- Activity records
- Adding new entries
r+ Mode
file = fopen("data.txt", "r+");
This mode allows reading and writing.
The file generally needs to exist.
When using update modes, pay attention to the current file position and sequencing between reading and writing operations.
w+ Mode
file = fopen("data.txt", "w+");
This allows reading and writing.
However, if the file already exists, its previous contents are truncated.
a+ Mode
file = fopen("data.txt", "a+");
This allows reading and appending.
The file is created if necessary, depending on the environment and mode semantics.
When reading after appending, use appropriate positioning functions such as rewind() or fseek() when needed.
Closing a File with fclose()
After finishing file operations, close the file:
fclose(file);
Example:
FILE *file; file = fopen("data.txt", "w"); if(file == NULL) { return 1; } fprintf(file, "Hello!"); fclose(file);
Closing a file is important because it:
- Releases resources.
- Flushes buffered output.
- Ends the stream cleanly.
Writing to a File with fprintf()
fprintf() works similarly to printf(), but writes formatted output to a file.
Syntax:
fprintf(file, "format", values);
Example:
#include <stdio.h> int main() { FILE *file; file = fopen("student.txt", "w"); if(file == NULL) { printf("Unable to open file.\n"); return 1; } fprintf(file, "Student ID: 101\n"); fprintf(file, "Name: Jitu\n"); fprintf(file, "Marks: 90.5\n"); fclose(file); return 0; }
The file may contain:
Student ID: 101 Name: Jitu Marks: 90.5
Writing Multiple Records
You can use loops with fprintf().
#include <stdio.h> int main() { FILE *file; int i; file = fopen("numbers.txt", "w"); if(file == NULL) { printf("Unable to open file.\n"); return 1; } for(i = 1; i <= 10; i++) { fprintf(file, "%d\n", i); } fclose(file); return 0; }
The file will contain numbers from 1 to 10.
Reading from a File with fscanf()
fscanf() works similarly to scanf(), but reads formatted data from a file.
Example:
#include <stdio.h> int main() { FILE *file; int number; file = fopen("numbers.txt", "r"); if(file == NULL) { printf("Unable to open file.\n"); return 1; } while(fscanf(file, "%d", &number) == 1) { printf("%d\n", number); } fclose(file); return 0; }
The return value of fscanf() indicates how many input items were successfully assigned. Testing it is more reliable than using while (!feof(file)).
Writing a Character with fputc()
The fputc() function writes one character.
Syntax:
fputc(character, file);
Example:
#include <stdio.h> int main() { FILE *file; file = fopen("letters.txt", "w"); if(file == NULL) { return 1; } fputc('A', file); fputc('B', file); fputc('C', file); fclose(file); return 0; }
The file will contain:
ABC
Reading a Character with fgetc()
The fgetc() function reads one character from a stream.
Example:
#include <stdio.h> int main() { FILE *file; int ch; file = fopen("letters.txt", "r"); if(file == NULL) { printf("Unable to open file.\n"); return 1; } while((ch = fgetc(file)) != EOF) { putchar(ch); } fclose(file); return 0; }
Notice that ch is an int, not a char.
This is important because fgetc() must be able to represent every possible unsigned character value and the special EOF value.
Writing Strings with fputs()
fputs() writes a string to a file.
Example:
#include <stdio.h> int main() { FILE *file; file = fopen("message.txt", "w"); if(file == NULL) { return 1; } fputs("Welcome to C Programming!\n", file); fputs("This is File Handling.\n", file); fclose(file); return 0; }
Reading Strings with fgets()
fgets() reads a line or a portion of a line from a stream.
Example:
#include <stdio.h> int main() { FILE *file; char line[100]; file = fopen("message.txt", "r"); if(file == NULL) { return 1; } while(fgets(line, sizeof(line), file) != NULL) { printf("%s", line); } fclose(file); return 0; }
This is a convenient approach for reading text line by line.
Understanding EOF
EOF stands for End of File.
It is a special value used by many input functions to indicate that no more input is available.
For example:
while((ch = fgetc(file)) != EOF) { putchar(ch); }
This means:
Continue reading characters until the end of the file is reached or an input error occurs.
feof() — End-of-File Indicator
C also provides:
feof(file)
It tests whether the stream's end-of-file indicator has been set.
A common beginner mistake is:
while(!feof(file)) { ... }
This is generally not the correct pattern for reading data.
Instead, let the input operation control the loop:
while(fgets(line, sizeof(line), file) != NULL) { printf("%s", line); }
or:
while((ch = fgetc(file)) != EOF) { putchar(ch); }
Appending Data to a File
Suppose students.txt contains:
101 Jitu 102 Rahim
Now you want to add:
103 Karim
Use append mode:
file = fopen("students.txt", "a");
Example:
#include <stdio.h> int main() { FILE *file; file = fopen("students.txt", "a"); if(file == NULL) { printf("Unable to open file.\n"); return 1; } fprintf(file, "103 Karim\n"); fclose(file); return 0; }
The previous data remains intact, and the new record is added.
Practical Program 1 — Create and Write a Text File
#include <stdio.h> int main() { FILE *file; file = fopen("welcome.txt", "w"); if(file == NULL) { printf("Error: Could not create file.\n"); return 1; } fprintf(file, "Welcome to ZAREEN TECH WAVE!\n"); fprintf(file, "C Programming Day 11\n"); fprintf(file, "Learning File Handling in C.\n"); fclose(file); printf("File created successfully.\n"); return 0; }
What This Program Does
-
Opens
welcome.txtin write mode. - Creates the file if necessary.
- Writes three lines.
- Closes the file.
- Displays a success message.
Practical Program 2 — Read a Text File
#include <stdio.h> int main() { FILE *file; char line[200]; file = fopen("welcome.txt", "r"); if(file == NULL) { printf("Error: Could not open file.\n"); return 1; } printf("===== File Content =====\n"); while(fgets(line, sizeof(line), file) != NULL) { printf("%s", line); } fclose(file); return 0; }
This program reads the file one line at a time.
Practical Program 3 — Append Data
#include <stdio.h> int main() { FILE *file; file = fopen("welcome.txt", "a"); if(file == NULL) { printf("Error: Could not open file.\n"); return 1; } fprintf(file, "This line was added later.\n"); fclose(file); printf("Data appended successfully.\n"); return 0; }
Practical Program 4 — Student Record System
Now let's combine structures and file handling.
#include <stdio.h> struct Student { int id; char name[50]; float marks; }; int main() { FILE *file; struct Student student; file = fopen("students.txt", "w"); if(file == NULL) { printf("Error opening file.\n"); return 1; } printf("Enter Student ID: "); scanf("%d", &student.id); printf("Enter Student Name: "); scanf("%49s", student.name); printf("Enter Marks: "); scanf("%f", &student.marks); fprintf(file, "%d %s %.2f\n", student.id, student.name, student.marks); fclose(file); printf("Student record saved successfully.\n"); return 0; }
This program connects today's lesson with Day 10 — Structures and Unions.
Practical Program 5 — Read Student Records
Suppose students.txt contains:
101 Jitu 85.50 102 Rahim 90.00 103 Karim 78.50
We can read the records using a structure.
#include <stdio.h> struct Student { int id; char name[50]; float marks; }; int main() { FILE *file; struct Student student; file = fopen("students.txt", "r"); if(file == NULL) { printf("Error opening file.\n"); return 1; } printf("===== Student Records =====\n"); while(fscanf(file, "%d %49s %f", &student.id, student.name, &student.marks) == 3) { printf("ID: %d\n", student.id); printf("Name: %s\n", student.name); printf("Marks: %.2f\n", student.marks); printf("--------------------\n"); } fclose(file); return 0; }
Practical Program 6 — Append Student Records
#include <stdio.h> struct Student { int id; char name[50]; float marks; }; int main() { FILE *file; struct Student student; file = fopen("students.txt", "a"); if(file == NULL) { printf("Error opening file.\n"); return 1; } printf("Enter Student ID: "); scanf("%d", &student.id); printf("Enter Student Name: "); scanf("%49s", student.name); printf("Enter Marks: "); scanf("%f", &student.marks); fprintf(file, "%d %s %.2f\n", student.id, student.name, student.marks); fclose(file); printf("Student record appended successfully.\n"); return 0; }
Practical Program 7 — Copy One File to Another
You can copy a text file character by character.
#include <stdio.h> int main() { FILE *source; FILE *destination; int ch; source = fopen("source.txt", "r"); if(source == NULL) { printf("Could not open source file.\n"); return 1; } destination = fopen("copy.txt", "w"); if(destination == NULL) { printf("Could not create destination file.\n"); fclose(source); return 1; } while((ch = fgetc(source)) != EOF) { fputc(ch, destination); } fclose(source); fclose(destination); printf("File copied successfully.\n"); return 0; }
Practical Program 8 — Count Characters in a File
#include <stdio.h> int main() { FILE *file; int ch; long count = 0; file = fopen("welcome.txt", "r"); if(file == NULL) { printf("Unable to open file.\n"); return 1; } while((ch = fgetc(file)) != EOF) { count++; } fclose(file); printf("Number of characters: %ld\n", count); return 0; }
This counts characters including whitespace characters such as spaces and newlines.
Practical Program 9 — Count Lines in a File
#include <stdio.h> int main() { FILE *file; int ch; long lines = 0; file = fopen("welcome.txt", "r"); if(file == NULL) { printf("Unable to open file.\n"); return 1; } while((ch = fgetc(file)) != EOF) { if(ch == '\n') { lines++; } } fclose(file); printf("Number of newline characters: %ld\n", lines); return 0; }
For general text processing, remember that the exact concept of a "line" can depend on the file's newline representation and whether the final line ends with a newline.
Practical Program 10 — Search for a Word
A simple line-based search can be implemented with strstr().
#include <stdio.h> #include <string.h> int main() { FILE *file; char line[200]; char word[50]; int found = 0; file = fopen("welcome.txt", "r"); if(file == NULL) { printf("Unable to open file.\n"); return 1; } printf("Enter word to search: "); scanf("%49s", word); while(fgets(line, sizeof(line), file) != NULL) { if(strstr(line, word) != NULL) { found = 1; break; } } fclose(file); if(found) printf("Word found in the file.\n"); else printf("Word not found.\n"); return 0; }
This is a basic substring search and is case-sensitive.
Useful File Functions in C
| Function | Purpose |
|---|---|
fopen() | Opens a file stream |
fclose() | Closes a file stream |
fprintf() | Writes formatted data |
fscanf() | Reads formatted data |
fputc() | Writes one character |
fgetc() | Reads one character |
fputs() | Writes a string |
fgets() | Reads a line/string |
feof() | Tests the EOF indicator |
ferror() | Tests the stream error indicator |
rewind() | Moves position to beginning |
fseek() | Changes file position |
ftell() | Reports current file position |
remove() | Deletes a file |
rename() | Renames a file |
Moving Around a File
C provides functions for controlling the current file position.
rewind()
rewind(file);
This moves the file position back to the beginning.
Example:
FILE *file = fopen("data.txt", "r+"); /* operations */ rewind(file);
fseek()
fseek() allows you to move the file position.
General form:
fseek(file, offset, origin);
Common origins include:
SEEK_SET SEEK_CUR SEEK_END
Example:
fseek(file, 0, SEEK_SET);
This moves to the beginning of the file.
ftell()
ftell() reports the current file position.
long position; position = ftell(file);
It is useful when you need to know where you currently are in a stream.
Error Handling
Good file-handling programs should check errors.
For example:
file = fopen("data.txt", "r"); if(file == NULL) { perror("Error opening file"); return 1; }
perror() prints a message describing the most recent library/system error associated with the current errno value.
For more advanced programs, ferror() can be used to determine whether a stream encountered an input/output error.
Example:
if(ferror(file)) { printf("A file error occurred.\n"); }
remove() — Delete a File
C provides:
remove("data.txt");
Example:
#include <stdio.h> int main() { if(remove("data.txt") == 0) { printf("File deleted successfully.\n"); } else { printf("Unable to delete file.\n"); } return 0; }
Be careful when using remove() because it deletes the named file.
rename() — Rename a File
You can rename a file with:
rename("old.txt", "new.txt");
Example:
#include <stdio.h> int main() { if(rename("old.txt", "new.txt") == 0) { printf("File renamed successfully.\n"); } else { printf("Unable to rename file.\n"); } return 0; }
Text File vs Binary File
| Feature | Text File | Binary File |
|---|---|---|
| Human-readable | Usually yes | Usually no |
| Common functions | fprintf(), fscanf(), fgets(), fputs() | fread(), fwrite() |
| Easy to inspect manually | Yes | No |
| Typical use | Logs, configuration, simple records | Structured binary data, media, efficient storage |
| Representation | Text characters | Binary representation |
For beginner C programs, text files are usually easier to understand and debug.
Common Mistakes in File Handling
1. Not Checking fopen()
Avoid:
file = fopen("data.txt", "r"); fprintf(file, "Hello");
If opening fails, file may be NULL.
Instead:
file = fopen("data.txt", "r"); if(file == NULL) { return 1; }
2. Forgetting fclose()
Always close files when you are finished:
fclose(file);
3. Accidentally Using w
Remember:
fopen("data.txt", "w");
can erase existing file contents by truncating the file.
If you want to preserve existing content and add new content, use:
fopen("data.txt", "a");
4. Using while(!feof(file))
Avoid this pattern for normal reading:
while(!feof(file))
Instead, check whether the input operation succeeds:
while(fgets(line, sizeof(line), file) != NULL)
or:
while((ch = fgetc(file)) != EOF)
5. Using char for fgetc()
Prefer:
int ch;
rather than:
char ch;
because fgetc() returns either an unsigned-character value converted to int or EOF.
Best Practices for File Handling
1. Always Check the File Pointer
if(file == NULL)
2. Close Every Successfully Opened File
fclose(file);
3. Choose the Correct Mode
Use:
r → read w → write/replace a → append
4. Avoid Unnecessary Data Loss
Be especially careful with w and w+.
5. Validate Input
Don't assume users always enter valid data.
6. Use Bounded Input
For fixed-size character arrays, avoid unbounded %s.
Prefer:
scanf("%49s", name);
for a char name[50].
7. Handle Errors Clearly
Use:
perror()
when appropriate.
8. Keep File Operations Organized
Separate tasks into functions such as:
saveStudent() loadStudents() appendStudent() displayStudents()
This makes larger projects easier to maintain.
Practice Problems
Beginner
-
Create a text file using
fopen(). - Write your name and address into a file.
- Read and display a text file.
- Write numbers from 1 to 100 to a file.
- Read numbers from a file.
- Count characters in a file.
- Count lines in a file.
- Count words in a text file.
Intermediate
- Create a student record file.
- Append new student records.
- Read all student records.
- Search for a student by ID.
- Search for a word in a text file.
- Copy one text file to another.
- Count vowels in a file.
- Count digits in a file.
- Count uppercase and lowercase letters.
- Calculate the average of numbers stored in a file.
Advanced
- Build a menu-driven student record system.
- Build an employee management system using files and structures.
- Build a product inventory system.
- Create a file-based contact management system.
- Add search, update, and delete functionality to a record system.
- Explore binary file operations with
fread()andfwrite().
Mini Project — File-Based Student Management System
A useful project after completing Day 11 is a Student Record Management System.
The program can provide a menu:
===== Student Management System =====1. Add Student 2. View Students 3. Search Student 4. Append Student 5. Exit
A student structure might be:
struct Student { int id; char name[50]; float marks; };
The program can save records into:
students.txt
This project combines concepts you've already learned:
Variables ↓ Input/Output ↓ Conditions ↓ Loops ↓ Arrays ↓ Functions ↓ Pointers ↓ Structures ↓ File Handling
You are now starting to build programs that can preserve information between executions.
Day 11 Summary
In C Programming Day 11, you learned the fundamentals of File Handling in C.
You learned:
- What file handling is
- Why files are useful
- Text files
- Binary files
- FILE *
- fopen()
- fclose()
- File modes
- r
- w
- a
- r+
- w+
- a+
- fprintf()
- fscanf()
- fputc()
- fgetc()
- fputs()
- fgets()
- EOF
- feof()
- ferror()
- rewind()
- fseek()
- ftell()
- remove()
- rename()
- File error handling
- Reading and writing text files
- Appending data
- Student record programs
- File-copy programs
- Character and line counting
- Practical file-based projects
The basic file-handling workflow is:
Open ↓ Check ↓ Read / Write / Append ↓ Close
Remember the three most important modes:
r → Read w → Write a → Append
Conclusion
Congratulations! 🎉 You have completed C Programming Day 11 — File Handling in C.
You now know how to make your C programs work with persistent data instead of relying only on temporary variables and arrays.
The most important functions to remember are:
fopen() fclose() fprintf() fscanf() fgetc() fputc() fgets() fputs()
You also learned why checking fopen() is important, how different file modes behave, how to read files safely, how to append information without overwriting existing content, and how to combine structures with file handling to create practical record-management applications.
This lesson is an important step toward building larger C projects because real-world programs often need to save and retrieve information.
In the final lesson of this course, we'll explore Dynamic Memory Allocation in C using malloc(), calloc(), realloc(), and free(), followed by practical programs and project ideas that bring together the concepts you've learned throughout the course.
Keep practicing, keep coding, and continue your C Programming journey!

Post a Comment
Thank You For Visit My Website.
I Will Contact As Soon As Possible.