C Write To Files
Learn how to write data to files in C programming
✍️ Writing to Files in C
File writing in C enables you to store data permanently using functions like fprintf(), fputs(), and fwrite(). You can write text, numbers, and structured data to files for data persistence and information storage.
#include <stdio.h>
int main() {
FILE *file = fopen("output.txt", "w");
fprintf(file, "Hello, File Writing!\n");
fclose(file);
return 0;
}
File Writing Functions
fprintf()
Write formatted data to files
fprintf(file, "Age: %d\n", 25);
fputs()
Write strings to files
fputs("Hello World", file);
fputc()
Write single characters to files
fputc('A', file);
fwrite()
Write binary data to files
fwrite(&data, sizeof(int), 1, file);
🔹 Writing Text with fprintf()
The fprintf() function writes formatted text to files with the same formatting capabilities as printf(). Specify format strings containing format specifiers for different data types, and fprintf() converts and writes values accordingly. This enables creating human-readable file content with precise formatting control. Always verify write success by checking return values, flush buffers when necessary to ensure data reaches disk, and close files properly to commit all written data.
#include <stdio.h>
int main() {
FILE *file;
char name[] = "John";
int age = 25;
float salary = 50000.50;
file = fopen("employee.txt", "w");
if (file != NULL) {
fprintf(file, "Employee Information\n");
fprintf(file, "Name: %s\n", name);
fprintf(file, "Age: %d\n", age);
fprintf(file, "Salary: %.2f\n", salary);
printf("Data written to file successfully!\n");
fclose(file);
}
return 0;
}
Output:
Data written to file successfully!
File content:
Employee Information Name: John Age: 25 Salary: 50000.50
🔹 Writing Strings with fputs()
The fputs() function writes entire strings to files efficiently without adding automatic newlines. Unlike puts() which adds a newline, fputs() writes exactly what you provide, giving precise control over output formatting. Use fputs() for writing complete lines, paragraph-like content, or when you control newline placement explicitly. Always check return values for write errors, handle cases where writes fail due to disk space or permission issues, and implement appropriate error recovery.
#include <stdio.h>
int main() {
FILE *file;
file = fopen("story.txt", "w");
if (file != NULL) {
fputs("Once upon a time...\n", file);
fputs("There was a programmer learning C.\n", file);
fputs("They mastered file handling!\n", file);
printf("Story written to file!\n");
fclose(file);
}
return 0;
}
Output:
Story written to file!
🔹 Writing Characters with fputc()
The fputc() function writes individual characters to files, useful for character-by-character output and custom formatting. Returns the written character on success or EOF on failure, enabling error detection immediately after each write. This approach works for building custom output formatting, writing character sequences with specific logic, or implementing character-based file generation algorithms. Handle write errors appropriately and implement efficient buffering when writing many characters sequentially.
#include <stdio.h>
int main() {
FILE *file;
char message[] = "HELLO";
int i;
file = fopen("chars.txt", "w");
if (file != NULL) {
// Write each character
for (i = 0; message[i] != '\0'; i++) {
fputc(message[i], file);
}
fputc('\n', file); // Add newline
printf("Characters written successfully!\n");
fclose(file);
}
return 0;
}
Output:
Characters written successfully!
🔹 Appending to Files
Opening files with append mode a preserves existing content while adding new data at the file end. Append mode moves the file pointer to the end automatically, enabling safe data addition without overwriting previous content. This is essential for log files, transaction records, and any applications requiring cumulative data storage. Always verify append operations succeed, implement error handling for failed appends, and consider file locking mechanisms in multi-process environments to prevent data corruption.
#include <stdio.h>
int main() {
FILE *file;
// Append to existing file
file = fopen("log.txt", "a");
if (file != NULL) {
fprintf(file, "New log entry: Program started\n");
fprintf(file, "Timestamp: 2024-01-15 10:30:00\n");
fprintf(file, "Status: OK\n\n");
printf("Log entry added!\n");
fclose(file);
}
return 0;
}
Output:
Log entry added!
🔹 Writing Multiple Records
Writing structured data like multiple student records to files requires looping through data and formatting each record appropriately. Create structures matching your data organization, iterate through record collections using loops, and write each record with fprintf() or fwrite() depending on text or binary storage needs. Implement consistent formatting so records can be read back accurately, handle partial write failures gracefully, and maintain data integrity throughout the writing process.
#include <stdio.h>
struct Student {
int id;
char name[50];
float grade;
};
int main() {
FILE *file;
struct Student students[3] = {
{1, "Alice", 85.5},
{2, "Bob", 92.0},
{3, "Charlie", 78.5}
};
int i;
file = fopen("students.txt", "w");
if (file != NULL) {
fprintf(file, "Student Records\n");
fprintf(file, "===============\n");
for (i = 0; i < 3; i++) {
fprintf(file, "ID: %d, Name: %s, Grade: %.1f\n",
students[i].id, students[i].name, students[i].grade);
}
printf("Student records written!\n");
fclose(file);
}
return 0;
}
Output:
Student records written!