
Write To Files in C
? Write to Files in C
In C, you can write data to files using the stdio.h
library and file handling functions like fopen()
, fprintf()
, fputs()
, and fwrite()
.
? Basic Steps to Write to a File
Include
stdio.h
Use
fopen()
with"w"
or"a"
modeWrite using
fprintf()
,fputs()
, orfwrite()
Close the file using
fclose()
? Example: Write Text to a File
#include <stdio.h>int main() { FILE *fptr; // Open file in write mode (creates file if it doesn't exist) fptr = fopen("example.txt", "w"); // Check if file was opened successfully if (fptr == NULL) { printf("Error opening file!\n"); return 1; } // Write to the file fprintf(fptr, "Hello, world!\n"); fputs("Writing to files in C is easy!\n", fptr); // Close the file fclose(fptr); printf("Data written to file successfully.\n"); return 0;}
? Modes in fopen()
Mode | Meaning |
---|---|
"w" | Write (creates or overwrites file) |
"a" | Append (adds to end of file) |
"w+" | Write + Read |
"a+" | Append + Read |
? Tips
Always check if the file opened successfully (
if (fptr == NULL)
).Don't forget to close the file after writing.