In C, files are treated as a stream of bytes. To manage a file, you must first open a connection to it using a File Pointer. Once the connection is established, you can perform operations like writing text, saving configurations, or logging errors.
The FILE structure contains information about the file being used. To create or open a file, we use the fopen() function, which takes two arguments: the filename and the mode.
The "mode" tells C exactly what you intend to do with the file. To create or write to a file, we primarily use these three modes:
| Mode | Meaning | Behavior |
|---|---|---|
"w" |
Write | Creates a new file. If the file exists, it overwrites all content. |
"a" |
Append | Adds data to the end of an existing file without deleting current content. |
"w+" |
Write/Read | Creates a file for both reading and writing. |
To write data into a file, we use fprintf() (formatted write) or fputs() (string write). After you are done, you **must** use fclose() to save your changes and free up memory.
If you use "w", your old data is deleted every time you run the program. To keep old data and add new text at the bottom, use the "a" mode.
Sometimes, creating a file fails (e.g., you don't have permission to write to a folder or the disk is full). In such cases, fopen() returns NULL. Always check your pointer before using it, or your program will crash with a "Segmentation Fault."
fclose(), data might stay in the buffer and never actually be written to the disk."w" when you meant "a" will result in irreversible data loss."wb" (write binary) if you are saving non-text data like images or encrypted files. This prevents the operating system from messing with newline characters.