String I/O with fgets and fputs
What you'll learn: How to safely read and write whole lines of text in files using the fgets and fputs functions.
Reading safely with fgets
When reading text from a file, we often want to grab an entire line at once. You might have seen fscanf, but it has a nasty habit: it stops at the first space it hits. If you want to read a full sentence like "Hello World," fscanf would only give you "Hello."
This is where fgets (File Get String) shines. It’s like a careful waiter who won't let your plate overflow. It takes three arguments: the character array to store the text, the maximum number of characters to read, and the file pointer. Because you tell it the size of your buffer, it prevents "buffer overflows," a common bug where data spills into memory it doesn't belong.
One quirk: fgets usually includes the newline character (\n) if there is room, so your string might come with a "hidden" enter key at the end.
Writing with fputs
Writing is even simpler. The fputs (File Put String) function takes a string and sends it to the file. Unlike printf, it doesn't do fancy formatting—it just dumps the raw text. It also doesn’t automatically add a newline, so if you want your next sentence on a new line, you must include the \n yourself.
A Practical Example
Imagine we have a file named notes.txt. Here is how we might read a line from it and then write that same line into a new file:
#include <stdio.h>
int main() {
FILE *source = fopen("notes.txt", "r");
FILE *dest = fopen("backup.txt", "w");
char buffer[100];
if (source != NULL && dest != NULL) {
// Read up to 99 characters (leaving 1 for the null terminator)
if (fgets(buffer, 100, source) != NULL) {
// Write the string we just read into the destination file
fputs(buffer, dest);
}
fclose(source);
fclose(dest);
}
return 0;
}
Why use these?
Think of fgets and fputs as the "safety-first" duo for text. By specifying a buffer size in fgets, you ensure your program won't crash even if the file contains a line that is a mile long. They are the standard tools for processing configuration files, logs, or any text document line-by-line.
Key takeaway
Use fgets to read lines safely by limiting input size, and fputs to write strings exactly as they are to a file.