Character I/O with fgetc and fputc
What you'll learn: How to read and write a text file one single letter at a time using two fundamental C functions.
The Fine-Toothed Comb
When dealing with files in C, you sometimes want to grab a whole line or a massive block of data. However, there are times when you need to be precise—like using a fine-toothed comb. This is where fgetc (file get character) and fputc (file put character) come in. They allow you to process a file at its most basic level: the individual character.
Think of a text file like a long strip of paper tape. fgetc is like a sensor that reads one letter and moves the tape forward by one notch. fputc is like a stamper that presses one letter onto the tape and then advances.
Using fgetc and fputc
To read a character, you call fgetc(file_pointer). It returns the character it found. To write one, you call fputc(character, file_pointer).
One critical detail: fgetc actually returns an int, not a char. This is because it needs to be able to return a special signal called EOF (End Of File) when it runs out of text. Since EOF isn't a normal letter, the function uses an integer to ensure it can signal "stop" clearly.
#include <stdio.h>
int main() {
FILE *source = fopen("hello.txt", "r");
FILE *dest = fopen("copy.txt", "w");
if (source == NULL || dest == NULL) {
return 1;
}
int ch; // Use int to hold the character and the EOF signal
// Read one character at a time until the end of the file
while ((ch = fgetc(source)) != EOF) {
// Write that same character to the new file
fputc(ch, dest);
}
fclose(source);
fclose(dest);
return 0;
}
Why use this?
While reading one character at a time might seem slow, it gives you ultimate control. If you wanted to change every 'a' to a '@' while copying a file, or count how many times the letter 'z' appears, character-by-character I/O is the simplest way to do it. You don't have to worry about how long the lines are or managing large memory buffers; you just handle one byte at a time until the job is done.
Key takeaway
Use fgetc to read and fputc to write a single character, always checking for EOF with an integer variable to know when the file ends.