C Files: Create and Write
Variables disappear when a program ends. To keep data, a program writes it to a file. In our editor, files your program creates appear in the file list, where you can open and download them.
Opening and writing a file
fopen(name, mode) opens a file and returns a FILE *, a pointer used by all file functions. Mode "w" creates the file, or empties it if it exists. fprintf writes to a file the way printf writes to the screen. fclose finishes the file.
#include <stdio.h>
int main(void) {
FILE *f = fopen("marks.txt", "w");
if (f == NULL) {
printf("Could not create marks.txt\n");
return 1;
}
fprintf(f, "Asha %d\n", 91);
fprintf(f, "Ravi %d\n", 78);
fputs("Meera 85\n", f);
fclose(f);
printf("marks.txt written.\n");
return 0;
}marks.txt written.
Always check for NULL: fopen fails when a folder does not exist or a file cannot be written, and using a NULL file pointer crashes the program.
File modes
| Mode | Meaning |
|---|---|
"r" | read an existing file |
"w" | write: create, or empty an existing file |
"a" | append: write at the end, create if missing |
"r+" | read and write an existing file |
"rb", "wb" | the same for binary (non-text) files |
Adding to a file
Mode "a" keeps what is in the file and adds at the end, which suits logs and lists that grow each time the program runs:
#include <stdio.h>
int main(void) {
for (int run = 1; run <= 3; run++) {
FILE *log = fopen("log.txt", "a");
if (log == NULL) return 1;
fprintf(log, "entry %d\n", run);
fclose(log);
}
FILE *f = fopen("log.txt", "r");
if (f == NULL) return 1;
char line[50];
while (fgets(line, sizeof line, f) != NULL) {
printf("%s", line);
}
fclose(f);
return 0;
}entry 1 entry 2 entry 3
Why fclose matters
Writing to a file is buffered: the data is collected in memory and written in larger pieces. fclose writes what is left and releases the file. If a program forgets fclose, the end of the data may never reach the file. A program can only have a limited number of files open, too.
Practice exercises
- Ask the user for three names and write each on its own line in
names.txt. - Write a multiplication table into
table.txt, then open the file in the editor. - Run a program with mode
"a"several times and watch the file grow.