C Notes
Complete guide to writing files in C — character writing with fputc, string writing with fputs, formatted output with fprintf, binary writing with fwrite, practical examples with output.
Once you've opened a file for writing, C gives you four main functions to put data into it. Each operates at a different level — single characters, strings, formatted text, or raw binary blocks. Choosing the right one makes your code cleaner and more efficient.
File Writing Functions Overview
| Function | Writes | Best For |
|---|---|---|
fputc() | One character | Character-by-character output |
fputs() | A string (no formatting) | Simple string output |
fprintf() | Formatted text | Numbers, tables, mixed data |
fwrite() | Binary block | Structs, arrays, raw data |
fputc() — Writing One Character
int fputc(int ch, FILE *stream);
// Returns: character written on success, EOF on errorAlphabet written to file. ABCDEFGHIJ KLMNOPQRST UVWXYZ
fputs() — Writing Strings
int fputs(const char *str, FILE *stream);
// Returns: non-negative on success, EOF on error
// NOTE: Does NOT add a newline automaticallyFile contents: The only way to learn C is to write C. Pointers are not hard, they're just different. Memory management is power and responsibility.
fprintf() — Formatted Writing (Most Versatile)
int fprintf(FILE *stream, const char *format, ...);
// Returns: number of characters written, or negative on errorReport written to report.txt
═══════════════════════════════════
SALES REPORT Q4 2024
═══════════════════════════════════
Product Units Revenue
─────────────── ────────── ──────────
Laptops 1250 1562500.00
Phones 3400 2720000.00
Tablets 890 534000.00
TOTAL 4816500.00fwrite() — Binary Block Writing
size_t fwrite(const void *ptr, size_t size, size_t count, FILE *stream);
// Returns: number of items successfully writtenWrote 3 records to binary file. Verification: 101 | Alice | 3.85 102 | Bob | 3.65 103 | Charlie | 3.92
Appending to Files
Log contents: [2024-12-15 14:30:01] Application started [2024-12-15 14:30:01] Loading configuration [2024-12-15 14:30:01] Ready to serve requests
Writing CSV Files
CSV written. Grand total: $131247.50
Error Checking on Write
#include <stdio.h>
int main() {
FILE *fp = fopen("output.txt", "w");
if (fp == NULL) return 1;
int result = fprintf(fp, "Test data\n");
if (result < 0) {
printf("Write error occurred!\n");
fclose(fp);
return 1;
}
// Check for write errors
if (ferror(fp)) {
printf("File error detected!\n");
}
fclose(fp);
printf("Written %d characters successfully.\n", result);
return 0;
}Written 10 characters successfully.
Interview Questions
Q1: What's the difference between fputs() and fprintf()?
fputs() writes a string as-is with no formatting. fprintf() supports format specifiers (%d, %f, %s) like printf. Use fputs for raw strings (slightly faster), fprintf when you need to embed variables or formatting.
Q2: Does fputs() add a newline at the end?
No! Unlike puts() which adds a newline, fputs() writes the string exactly as given. You must include \n in the string if you want a newline.
Q3: How do you ensure data is written to disk immediately?
Call fflush(fp) after writing. This forces the C library buffer to be written to the OS. For even stronger guarantees (OS cache to disk), use OS-specific calls like fsync() on Linux.
Q4: What happens if you write to a file opened with "r" mode?
The behavior is undefined. On most systems, the write functions will either do nothing or return an error. Always use "w", "a", or a "+" mode for writing.
Summary
fputc()— write single characters (loops, encryption, encoding)fputs()— write complete strings (no formatting, no newline added)fprintf()— formatted output to files (most versatile)fwrite()— binary data (structs, arrays, exact byte representation)- Use "a" mode for log files to avoid destroying existing data
- Always check return values for write errors
- Use
fflush()when you need immediate disk persistence
Exam Focus
Revise definitions, diagrams, examples, and short-answer points for Writing Files in C – fputc, fputs, fprintf, fwrite.
Interview Use
Prepare one clear explanation, one practical example, and one common mistake for this C Programming topic.
Search Terms
c-programming, c programming, programming, file, handling, writing, files, writing files in c – fputc, fputs, fprintf, fwrite
Related C Programming Topics