C Write To Files
Introduction to Writing Files
Writing to files allows programs to store data persistently. C provides several functions for writing data to files, each suited for different types of data and formatting needs. Understanding these functions is essential for creating programs that can save output, create reports, or store configuration data.
Common File Writing Functions
Function | Description | Best For |
---|---|---|
fputc() | Writes a single character | Character-by-character output |
fputs() | Writes a string (without formatting) | Writing complete strings |
fprintf() | Formatted output (like printf but to file) | Formatted text output |
fwrite() | Writes raw binary data | Binary files and structured data |
File Open Modes for Writing
Choose the right mode when opening a file:
• "w" – Create/truncate text file for writing
• "a" – Append to text file (create if missing)
• "w+" – Read/write, truncate if exists
• "a+" – Read/append (writes go to end)
Add "b" for binary on platforms that distinguish text vs. binary (e.g., "wb", "ab").
fputc() - Writing Single Characters
Example
#include <stdio.h>
int main(void) {
FILE *file = fopen("chars.txt", "w");
if (file == NULL) {
printf("Error opening file.");
return 1;
}
fputc('H', file);
fputc('e', file);
fputc('l', file);
fputc('l', file);
fputc('o', file);
fputc('\n', file);
fclose(file);
printf("Characters written to file.");
return 0;
}
Output
Characters written to file.
ℹ️ Note: fputc() returns the character written or EOF on error. Always check for errors in production code.
fputs() - Writing Strings
⚠️ Warning: fputs() does not automatically add a newline character. You must include it in your strings if needed.
Example
#include <stdio.h>
int main(void) {
FILE *file = fopen("strings.txt", "w");
if (file == NULL) {
printf("Error opening file.");
return 1;
}
fputs("Hello World!\n", file);
fputs("This is a test.\n", file);
fputs("File writing in C.\n", file);
fclose(file);
printf("Strings written to file.");
return 0;
}
Output
Strings written to file.
fprintf() - Formatted Writing
Example
#include <stdio.h>
int main(void) {
FILE *file = fopen("formatted.txt", "w");
if (file == NULL) {
printf("Error opening file.");
return 1;
}
char name[] = "Alice";
int age = 25;
float salary = 55000.50f;
fprintf(file, "Name: %s\n", name);
fprintf(file, "Age: %d years\n", age);
fprintf(file, "Salary: $%.2f\n", salary);
fprintf(file, "Formatted date: %02d/%02d/%04d\n", 12, 5, 2023);
fclose(file);
printf("Formatted data written to file.");
return 0;
}
Output
Formatted data written to file.
ℹ️ Note: fprintf() works exactly like printf() but writes to a file instead of stdout.
Appending to a File (a mode)
Example
#include <stdio.h>
int main(void) {
FILE *log = fopen("app.log", "a");
if (!log) { perror("open"); return 1; }
fprintf(log, "Started app\n");
fprintf(log, "Processing item %d\n", 42);
if (fclose(log) == EOF) { perror("close"); return 1; }
printf("Log entries appended.");
return 0;
}
Output
Log entries appended.
ℹ️ Note: In append mode, all writes go to the end of the file regardless of the current file position.
fwrite() - Binary Writing
⚠️ Warning: Binary files are not human-readable and may not be portable between different systems or architectures. Always check the return value of fwrite().
Example
#include <stdio.h>
#include <string.h>
struct Employee {
int id;
char name[50];
float salary;
};
int main(void) {
FILE *file = fopen("employees.bin", "wb");
if (file == NULL) {
perror("open");
return 1;
}
struct Employee employees[2] = {
{101, "John Doe", 45000.75f},
{102, "Jane Smith", 52000.00f}
};
size_t written = fwrite(employees, sizeof(struct Employee), 2, file);
if (written != 2) {
perror("fwrite");
fclose(file);
return 1;
}
if (fclose(file) == EOF) { perror("close"); return 1; }
printf("Binary data written to file.");
return 0;
}
Output
Binary data written to file.
Error Handling in File Writing
Example
#include <stdio.h>
int main(void) {
FILE *file = fopen("output.txt", "w");
if (file == NULL) {
perror("Error opening file");
return 1;
}
if (fputs("Important data\n", file) == EOF) {
perror("Error writing to file");
fclose(file);
return 1;
}
if (fprintf(file, "Value: %d\n", 42) < 0) {
perror("Error writing formatted data");
fclose(file);
return 1;
}
if (fclose(file) == EOF) {
perror("Error closing file");
return 1;
}
printf("All operations completed successfully.");
return 0;
}
Output
All operations completed successfully.
ℹ️ Note: Always check return values of file operations and use perror() for meaningful error messages.