fputc(ch, fp) writes one character, fputs(str, fp) writes a string without adding a newline, and fprintf(fp, format, ...) writes formatted text. Output is buffered, so call fclose or fflush to make sure it reaches the file.
Remember
fputc('A', fp);
fputs("text\n", fp);
fprintf(fp, "%d squared is %d\n", n, n * n);
fflush(fp); /* force buffered data out */
Reference
Cheat Sheet
Keep these facts handy while you work with Writing Text Files in C.
Topic
Detail
fputc
One character
fputs
No newline added
fprintf
Formatted
Buffering
fflush / fclose
Code
C Examples
Compile each example with gcc file.c -std=c11 -Wall -o out. Next: Formatted File I/O.
Example 1 — Write a table of squares
Write with fprintf, then read the first line back.
C
#include <stdio.h>
int main(void) {
FILE *fp = fopen("squares.txt", "w");
if (!fp) return 1;
for (int n = 1; n <= 3; n++) {
fprintf(fp, "%d squared is %d\n", n, n * n);
}
fclose(fp);
printf("wrote 3 lines\n");
char line[64];
fp = fopen("squares.txt", "r");
if (!fp) return 1;
if (fgets(line, sizeof line, fp)) printf("first: %s", line);
fclose(fp);
return 0;
}
Output
wrote 3 lines
first: 1 squared is 1
How It Works
fprintf works like printf but targets a file.
fclose makes sure everything is on disk.
The second open reads the first line back.
Edge Cases & Pitfalls
Check these before relying on Writing Text Files in real programs.
nl
Forgetting newlines
fputs does not append \n, unlike puts.
loss
Output lost on crash
Buffered data is lost if the program crashes before fflush or fclose.
Remember
Key Takeaways
fprintf: most flexible.
fputs: no newline.
Flush: before risky operations.
One line: fputc(ch, fp) writes one character, fputs(str, fp) writes a string without adding a newline, and fprintf(fp, format, ...) writes formatted text.
Frequently Asked Questions
puts writes to stdout and appends a newline. fputs writes to the stream you give it and does not add a newline.
Open it in "a" mode so every write goes to the end.
Continue with "C Formatted File I/O" next. Write and parse records with fprintf and fscanf. The C File Handling hub lists every topic in order.