✍️ C Write to Files – Output Data to Text and Binary Files in C
🧲 Introduction – How to Write to Files in C?
In C programming, writing to files enables a program to store data persistently in external files. Whether you’re saving logs, exporting reports, or storing raw binary data, C provides standard functions like fprintf(), fputs(), and fwrite() to perform file output operations.
🎯 In this guide, you’ll learn:
- How to open files for writing
- Write to text files using
fprintf()andfputs() - Write to binary files using
fwrite() - Handle common writing errors and close files properly
📁 Opening Files for Writing
Before writing to a file, it must be opened in write mode using fopen(). Writing modes:
| Mode | Description |
|---|---|
"w" | Write text file (overwrite if exists) |
"a" | Append text at end of file |
"wb" | Write binary file (overwrite) |
"ab" | Append to binary file |
FILE *fp = fopen("output.txt", "w");
if (fp == NULL) {
perror("Error opening file");
}
🖊️ Writing to Text Files
✅ fprintf() – Formatted Output
FILE *fp = fopen("data.txt", "w");
fprintf(fp, "Name: %s\nAge: %d\n", "Alice", 30);
fclose(fp);
- Behaves like
printf()but writes to a file - Supports format specifiers (
%s,%d,%f, etc.)
✅ fputs() – Write String to File
FILE *fp = fopen("log.txt", "a");
fputs("Log entry: Program started.\n", fp);
fclose(fp);
- Writes a string (without format control)
- Faster and simpler than
fprintf()for plain strings
💾 Writing to Binary Files
✅ fwrite() – Write Raw Data
FILE *fp = fopen("data.bin", "wb");
int numbers[] = {10, 20, 30};
fwrite(numbers, sizeof(int), 3, fp);
fclose(fp);
Syntax:
fwrite(pointer, size_of_each_element, number_of_elements, file_pointer);
- Writes raw memory as-is into the file
- Ideal for compact storage and structured records
❗ Error Handling While Writing
Always verify that the file is opened and written successfully:
FILE *fp = fopen("file.txt", "w");
if (fp == NULL) {
perror("Failed to open file");
return 1;
}
if (fprintf(fp, "Hello") < 0) {
printf("Write failed!\n");
}
fclose(fp);
🧠 Use Cases
| Task | Function |
|---|---|
| Writing logs | fputs() |
| Exporting reports | fprintf() |
| Saving binary data | fwrite() |
| Appending entries | "a" or "ab" mode |
| Writing configuration | fprintf() |
💡 Best Practices & Tips
📘 Best Practice:
Always close the file using fclose() after writing to ensure buffers are flushed and file descriptors released.
💡 Tip:
Use "a" or "ab" mode to preserve existing data and append new content.
⚠️ Pitfall:
Opening a file in "w" or "wb" overwrites its content if it already exists.
📌 Summary – Recap & Next Steps
Writing to files in C is a core part of building persistent, user-driven applications. Whether using formatted text or binary output, you can control how data is saved and organized externally.
🔍 Key Takeaways:
- Use
fopen("file.txt", "w")or"wb"to write files fprintf()andfputs()are for text outputfwrite()is used for binary output- Always check file opening success and close files properly
⚙️ Real-World Relevance:
Used in loggers, data exporters, binary storage tools, report generation, and embedded device state storage.
❓ Frequently Asked Questions (FAQ)
❓ How do I write to a text file in C?
✅ Use fopen() with "w" or "a" mode, then write using fprintf() or fputs().
❓ How can I write binary data to a file?
✅ Use fopen() with "wb" mode and write with fwrite().
❓ What happens if I open an existing file in "w" mode?
❌ It gets overwritten, and all previous content is lost.
❓ Is fprintf() safer than fputs()?
✅ fprintf() offers format control, while fputs() is simpler for plain strings. Both are safe if used correctly.
❓ Can I write multiple types of data in one file?
✅ Yes. Use fprintf() for formatted text or fwrite() with structs for binary.
Share Now :
