File Handling Programs in C
You now know every file function. This lesson puts them together in the complete programs that lab exams and practicals ask for again and again: copying a file, counting characters, words and lines, appending, merging two files, and converting text to uppercase.
Each program follows the same safe pattern: open, check, process, close. Learn the pattern once and you can write any file program.
What You Will Learn
- A reusable pattern for file programs.
- How to copy one file to another.
- How to count characters, words and lines in a file.
- How to append to an existing file.
- How to merge two files into a third.
- How to transform a file (uppercase).
The File Program Pattern
Exam definition: A typical file-processing program opens the source file in read mode and the destination in write/append mode, checks both for NULL, processes data in a loop until the read function signals end of file, and closes every file it opened.
Memory trick: Every file program is a water pipe: source tank (read file) → pipe (your loop, maybe with a filter like toupper) → destination tank (write file). Check both tanks exist before you open the tap, and close both taps at the end.
src = fopen(source, "r") dst = fopen(dest, "w" or "a")
if either is NULL -> report, close the other, stop
while ((ch = fgetc(src)) != EOF) (or fgets / fread)
process ch, maybe fputc(ch, dst)
fclose(src); fclose(dst)
For these demos, each program first creates its own sample input file, so you can run it anywhere. In a real program, the file would already exist and its name might come from the user.
Example 1: Copy a File and Count Characters, Words and Lines
#include <stdio.h>
#include <ctype.h>
int copy_file(const char *from, const char *to)
{
FILE *src = fopen(from, "r");
FILE *dst;
int ch;
if (src == NULL)
return 0;
dst = fopen(to, "w");
if (dst == NULL)
{
fclose(src);
return 0;
}
while ((ch = fgetc(src)) != EOF)
fputc(ch, dst);
fclose(src);
fclose(dst);
return 1;
}
void count_file(const char *name)
{
FILE *fp = fopen(name, "r");
int ch, chars = 0, words = 0, lines = 0, in_word = 0;
if (fp == NULL)
return;
while ((ch = fgetc(fp)) != EOF)
{
chars++;
if (ch == '\n')
lines++;
if (isspace(ch))
in_word = 0;
else if (!in_word)
{
in_word = 1;
words++;
}
}
fclose(fp);
printf("%s: %d characters, %d words, %d lines\n", name, chars, words, lines);
}
int main(void)
{
FILE *fp = fopen("source.txt", "w");
if (fp == NULL)
return 1;
fputs("Practice makes a programmer perfect.\n", fp);
fputs("Write code every day.\n", fp);
fclose(fp);
if (copy_file("source.txt", "copy.txt"))
printf("Copied source.txt to copy.txt\n");
count_file("source.txt");
count_file("copy.txt");
remove("source.txt");
remove("copy.txt");
return 0;
}
Output
Copied source.txt to copy.txt source.txt: 59 characters, 9 words, 2 lines copy.txt: 59 characters, 9 words, 2 lines
Code Explanation
copy_fileopens the source first. If the destination can't be opened, it closes the source before returning, so nothing is left open.- The copy loop moves one character at a time with
fgetc/fputc. This copies text exactly, including newlines. count_filecounts characters, lines ('\n') and words (the start of each non-space run).- Identical counts for both files prove the copy is exact.
- To copy any file (images, PDFs), open with
"rb"and"wb", or copy blocks withfread/fwrite.
How Append and Merge Work
- Append: open the existing file with
"a"; every write lands at the end, and old content stays. - Merge: open the output with
"w", then copy file 1 into it, then copy file 2 into it, using the same loop twice. - Transform: same copy loop, but change each character before writing it (for example,
toupper(ch)).
Example 2: Append, Merge and Convert to Uppercase
#include <stdio.h>
#include <ctype.h>
void write_text(const char *name, const char *mode, const char *text)
{
FILE *fp = fopen(name, mode);
if (fp == NULL)
return;
fputs(text, fp);
fclose(fp);
}
void append_file(FILE *dst, const char *name, int upper)
{
FILE *src = fopen(name, "r");
int ch;
if (src == NULL)
return;
while ((ch = fgetc(src)) != EOF)
fputc(upper ? toupper(ch) : ch, dst);
fclose(src);
}
void print_file(const char *name)
{
char line[100];
FILE *fp = fopen(name, "r");
if (fp == NULL)
return;
printf("--- %s ---\n", name);
while (fgets(line, sizeof line, fp) != NULL)
printf("%s", line);
fclose(fp);
}
int main(void)
{
FILE *out;
write_text("fruits.txt", "w", "apple\nmango\n");
write_text("fruits.txt", "a", "banana\n"); /* append */
write_text("veggies.txt", "w", "carrot\npotato\n");
print_file("fruits.txt");
out = fopen("all.txt", "w"); /* merge */
if (out == NULL)
return 1;
append_file(out, "fruits.txt", 0);
append_file(out, "veggies.txt", 0);
fclose(out);
print_file("all.txt");
out = fopen("ALL_CAPS.txt", "w"); /* transform */
if (out == NULL)
return 1;
append_file(out, "all.txt", 1);
fclose(out);
print_file("ALL_CAPS.txt");
remove("fruits.txt");
remove("veggies.txt");
remove("all.txt");
remove("ALL_CAPS.txt");
return 0;
}
Output
--- fruits.txt --- apple mango banana --- all.txt --- apple mango banana carrot potato --- ALL_CAPS.txt --- APPLE MANGO BANANA CARROT POTATO
- "banana" was added with mode
"a", so apple and mango survived. append_filetakes an already open destination, so the merge writes file 1 and then file 2 into the same output.- Passing
upper = 1reuses the same loop as a filter that converts to capitals.
More File Programs to Practise
| Program | Key idea |
|---|---|
| Count vowels in a file | fgetc + check tolower(ch) in "aeiou" |
| Display a file in reverse | fseek to the end, step back with fseek(fp, -k, SEEK_END) |
| Search a word in a file | fgets each line + strstr |
| Delete a specific line | Copy every other line to a temp file, then remove + rename |
| Compare two files | Read both with fgetc in step; report the first mismatch |
| Student database | Binary records with fwrite/fread/fseek |
See also: write and read a text file.
Important Points to Remember
- Pattern: open → check → loop until EOF → close.
- If the second fopen fails, close the first file.
- Copy text with fgetc/fputc; copy any file with "rb"/"wb".
- Append with "a"; merge by copying two sources into one "w" file.
- Transform data in the middle of the copy loop.
- Use remove and rename to replace a file safely.
Common Mistakes Beginners Make
| Mistake | What happens | Fix |
|---|---|---|
| Opening the output with "w" when it's also the input | Input is erased before reading | Write to a temp file, then rename |
| Not closing the source when the destination fails | File stays open (resource leak) | Close it before returning |
Using char ch in the copy loop | Copy may stop early on some bytes | int ch |
| Copying a binary file in text mode (Windows) | Corrupted copy | Use "rb" and "wb" |
| Merging with "a" on an old output file | Data from previous runs remains | Open output with "w" first |
File Programs Practice Questions
- Write the loop that copies one text file to another.
- How would you merge three files into one?
- Why must the source be closed if the destination can't be opened?
- How can you safely delete one line from a file?
- What changes are needed to copy an image file?
Show answers
while ((ch = fgetc(src)) != EOF) fputc(ch, dst);- Open the output with "w", then copy file 1, file 2 and file 3 into it one after another.
- Otherwise it stays open: a resource leak (and possibly a locked file).
- Copy every line except that one to a temporary file, remove the original, then rename the temp file to the original name.
- Open both files in binary mode ("rb", "wb"), ideally copying blocks with fread/fwrite.
Coding Exercise
Create a file with the text "Engineering students love C programming\n". Read it with fgetc and print the number of vowels and consonants.
Show solution
#include <stdio.h>
#include <ctype.h>
int main(void)
{
FILE *fp = fopen("line.txt", "w");
int ch, vowels = 0, consonants = 0;
if (fp == NULL)
return 1;
fputs("Engineering students love C programming\n", fp);
fclose(fp);
fp = fopen("line.txt", "r");
if (fp == NULL)
return 1;
while ((ch = fgetc(fp)) != EOF)
{
if (isalpha(ch))
{
int c = tolower(ch);
if (c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u')
vowels++;
else
consonants++;
}
}
fclose(fp);
printf("Vowels: %d, Consonants: %d\n", vowels, consonants);
remove("line.txt");
return 0;
}
Vowels: 12, Consonants: 23
Quick Quiz: File Handling Programs (MCQ)
-
To add lines to the end of an existing file, open it with:
A)
"w"B)"a"C)"r"D)"rb" -
The standard loop to copy characters is:
A)
while (!feof(src))B)while ((ch = fgetc(src)) != EOF)C)for (;;) fgetc(src);D)while (fputc(ch, dst)) -
To rename a file in C, use:
A)
move()B)rename()C)fcopy()D)chname() -
A word counter usually counts:
A) Spaces + 1 always B) Starts of non-space runs C) Newlines D) Characters / 5
-
Function that deletes a file:
A)
delete()B)remove()C)fclose()D)unlinkall()
Show answers
- B:
"a". - B.
- B:
rename(). - B: starts of non-space runs (works with extra spaces too).
- B:
remove().
Quick Revision for Exams and Interviews
Read this before your exam. The highlighted words are the answer.
Must-remember facts
| Pattern | Open → check → loop → close |
|---|---|
| Copy loop | while ((ch = fgetc(s)) != EOF) fputc(ch, d); |
| Append | Mode "a" |
| Merge | Copy file 1 then file 2 into one "w" file |
| Count words | Count starts of words |
| Binary copy | "rb" / "wb" |
| Delete / rename | remove() / rename() |
Frequently asked questions
- How do you copy a file in C?
- Open source in "r" and target in "w", then fgetc/fputc until EOF, and close both.
- How do you count words in a file?
- Read characters and count each time a non-space character follows a space (or the start).
- How do you merge two files?
- Open the output once in "w" mode and copy both files into it one after the other.
Remember
- File program = water pipe: source → loop → destination.
- Check both tanks, close both taps.
Next Topic
Next lesson: Preprocessor Directives in C. You will start Module 14 and learn how the preprocessor works with #include, #define and #if.