Opening and closing files in C
fopen returns NULL on failure, and every successful open needs a matching close.
#include <stdio.h>
int write_greeting(const char *path) {
FILE *f = fopen(path, "w");
if (f == NULL) {
return 0;
}
fprintf(f, "hello from C\n");
return fclose(f) == 0;
}
long file_size(const char *path) {
FILE *f = fopen(path, "rb");
if (f == NULL) {
return -1;
}
fseek(f, 0, SEEK_END);
long size = ftell(f);
fclose(f);
return size;
}
How it works
- The mode string picks read, write, append and text or binary.
- Mode
wtruncates an existing file, whileaappends to it. - Checking for NULL is not optional.
Keywords and builtins used here
FILENULLcharconstfile_sizeifintlongreturnwrite_greeting
The run, in numbers
- Lines
- 21
- Characters to type
- 336
- Tokens
- 117
- Three-star pace
- 95 tpm
At the three-star pace of 95 tokens a minute, this run takes about 74 seconds.
Step 1 of 4 in Opening & reading, step 1 of 12 in Files & I/O.