C Write To Files
1. Opening a File for Writing
Use fopen() with a write mode:
| Mode | Description |
|---|---|
"w" |
Write (creates a new file or overwrites existing file) |
"a" |
Append (adds data to end of file, creates file if it doesn’t exist) |
"w+" |
Read & write (creates or overwrites file) |
"a+" |
Read & append (creates file if doesn’t exist) |
2. Writing Functions in C
| Function | Description |
|---|---|
fputc(ch, fp) |
Writes a single character to the file |
fputs(str, fp) |
Writes a string to the file |
fprintf(fp, "format", variables) |
Writes formatted output (like printf) |
3. Example 1: Writing a String Using fputs
Output in file output.txt:
4. Example 2: Writing a Single Character Using fputc
Output in file charfile.txt:
5. Example 3: Writing Formatted Data Using fprintf
Output in file data.txt:
6. Example 4: Appending Data to a File
-
The new line is added at the end without overwriting existing data.
7. Key Points About Writing to Files
-
Use write (
w) to overwrite or append (a) to add data. -
Always check if
fopensucceeded. -
Close the file using
fclose()after writing. -
Functions for writing:
-
fputc()→ single character -
fputs()→ string -
fprintf()→ formatted output
-
-
Appending ensures existing data is preserved.
