C Create and Write Files
Creating and writing files means saving data from a C program onto disk. In C, you open a file, write data through a FILE * pointer, and close the file when you are finished.
File writing is useful when a program needs to save reports, settings, logs, scores, or any data that should remain after the program ends.
Open A File For Writing
The fopen function opens a file and returns a file pointer. To create or replace a text file, use mode "w", which means write mode.
FILE *file = fopen("message.txt", "w");
If the file does not exist, C tries to create it. If it already exists, write mode clears its old contents before writing new data. If opening fails, fopen returns NULL.
Write Text With fprintf
The fprintf function works like printf, but it writes to a file instead of the screen. Its first argument is the file pointer.
#include <stdio.h>
int main(void)
{
FILE *file = fopen("message.txt", "w");
if (file == NULL) {
printf("Could not open file.\n");
return 1;
}
fprintf(file, "Hello from C!\n");
fprintf(file, "This line was written to a file.\n");
fclose(file);
printf("File written.\n");
return 0;
}
Output:
File written.
When this program runs successfully, it creates a file named message.txt in the program’s working directory. The text is saved in the file, while only File written. is printed on the screen.
How The Example Works
The variable file stores the file pointer returned by fopen. The program checks file == NULL before writing because files can fail to open, for example because of permissions or an invalid path.
Each fprintf call writes one line to the file. The \n newline characters are saved in the file just like they would be printed on the screen by printf.
The call fclose(file); closes the file. Closing a file is important because it finishes pending writes and releases the file resource.
Writing Values To A File
You can use format specifiers with fprintf to write variable values. This is useful for saving calculated results or table-like data.
#include <stdio.h>
int main(void)
{
FILE *file = fopen("scores.txt", "w");
int scores[3] = {90, 85, 92};
int i;
if (file == NULL) {
printf("Could not open file.\n");
return 1;
}
for (i = 0; i < 3; i++) {
fprintf(file, "Student %d: %d\n", i + 1, scores[i]);
}
fclose(file);
printf("Saved 3 scores.\n");
return 0;
}
Output:
Saved 3 scores.
The loop writes three formatted lines to scores.txt. The file contents would contain the student number and score for each array element.
Other Writing Functions
C also provides smaller writing functions. Use fputs to write a string and fputc to write one character.
#include <stdio.h>
int main(void)
{
FILE *file = fopen("letters.txt", "w");
if (file == NULL) {
printf("Could not open file.\n");
return 1;
}
fputs("Letters: ", file);
fputc('A', file);
fputc('B', file);
fputc('C', file);
fputc('\n', file);
fclose(file);
printf("Letters saved.\n");
return 0;
}
Output:
Letters saved.
fputs does not automatically add a newline, so add \n yourself when you want one. fputc writes exactly one character.
Common File Modes
| Mode | Meaning |
|---|---|
"w" |
Open for writing. Create the file if needed. Clear old contents if it exists. |
"a" |
Open for appending. New data goes at the end of the file. |
"r" |
Open for reading. The file must already exist. |
This lesson focuses on "w". Appending and reading are covered separately because they have different behavior.
Important Rules
- Include
<stdio.h>before using file functions. - Use a
FILE *variable to store the file pointer. - Check whether
fopenreturnedNULLbefore writing. - Use
fprintffor formatted text,fputsfor strings, andfputcfor single characters. - Call
fclosewhen you are done with the file. - Remember that
"w"overwrites an existing file’s contents.
The key idea is that C writes files through a file pointer: open the file, write data, check for errors, and close the file when finished.
