
Create Files in C
Creating files in C is done using the standard I/O library <stdio.h>
. You can create, write to, or read from files using functions like fopen()
, fprintf()
, fputs()
, etc. ??
? Basic Steps to Create a File in C
Include the header:
#include <stdio.h>
Use
fopen()
with"w"
mode to create/write a fileUse functions like
fprintf()
orfputs()
to write to itClose the file with
fclose()
? Example: Create and Write to a File
#include <stdio.h>int main() { FILE *file; // Open file in write mode ("w" = write) file = fopen("example.txt", "w"); // Check if file opened successfully if (file == NULL) { printf("? Error creating file.\n"); return 1; } // Write text into the file fprintf(file, "Hello from C!\n"); fputs("This is another line.\n", file); // Close the file fclose(file); printf("? File created and written successfully.\n"); return 0;}
? File Modes in fopen()
Mode | Meaning |
---|---|
"w" | Create/overwrite (write) |
"a" | Append (write at end) |
"r" | Read only |
"w+" | Create for read/write |
"a+" | Read/append (create if not exist) |
"r+" | Read/write (file must exist) |
?? Notes
"w"
mode overwrites the file if it already exists.Always check if the
FILE *
pointer isNULL
before writing.Use
fclose()
to avoid file corruption or memory leaks.