Files
Error Checks
File code checks whether fopen succeeded before using the stream.
Error Checks
error_checks.c
#include <stdio.h>
int main(void) {
int createFile = ;
const char *path = "error_checks_demo.txt";
if (createFile) {
FILE *created = fopen(path, "w");
if (created != 0) {
fputs("ok\n", created);
fclose(created);
}
}
FILE *file = fopen(path, "r");
int opened = (file != 0);
if (file != 0) {
fclose(file);
remove(path);
}
printf("opened=%d\n", opened);
return 0;
}
#include <stdio.h>
int main(void) {
int createFile = ;
const char *path = "error_checks_demo.txt";
if (createFile) {
FILE *created = fopen(path, "w");
if (created != 0) {
fputs("ok\n", created);
fclose(created);
}
}
FILE *file = fopen(path, "r");
int opened = (file != 0);
if (file != 0) {
fclose(file);
remove(path);
}
printf("opened=%d\n", opened);
return 0;
}
open failure
`fopen` returns `0` when it cannot open the requested file.
guarded use
Only pass a stream to I/O functions after checking that it is not `0`.