Writing to a file involves three distinct steps: Opening the file in a writable mode, Sending the data through a stream, and Closing the file to flush the buffer and save changes.
C provides different functions depending on whether you want to write formatted text, simple strings, or single characters.
printf(), but writes to a file instead of the console. Great for formatted data (integers, floats).fprintf() for plain text.Here is how you would write structured data into a text file named data.txt:
Understanding the file mode is critical. Choosing the wrong one can result in losing existing data.
| Mode | Action | Risk Level |
|---|---|---|
"w" (Write) |
Deletes old content and starts fresh. | High (Data loss) |
"a" (Append) |
Keeps old content; adds new data to the end. | Low (Safe) |
When you write to a file, C doesn't always send the data to the disk immediately. It stores it in a small "buffer" in RAM to improve speed. fclose() performs a "flush," forcing any remaining data in the buffer to be written to the physical storage device.
If you need to write an entire array or a struct to a file at once, professional C developers use fwrite(). This writes data in binary format, which is much faster and takes up less space than text.
\n at the end of your fprintf or fputs calls if you want the next piece of data to appear on a new line. Unlike puts() in the console, fputs() does not add a newline automatically!