errno and perror in C
When a call fails, errno says why, and perror prints it with your prefix.
#include <errno.h>
#include <stdio.h>
#include <string.h>
int open_or_report(const char *path) {
errno = 0;
FILE *f = fopen(path, "r");
if (f == NULL) {
perror("fopen");
fprintf(stderr, " (%s: %s)\n", path, strerror(errno));
return 0;
}
fclose(f);
return 1;
}
How it works
- Set
errnoto zero before the call you intend to test. perrorwrites to stderr;strerrorgives you the text.- Only check errno after a call that reported failure.
Keywords and builtins used here
FILENULLcharconstifintopen_or_reportreturn
The run, in numbers
- Lines
- 15
- Characters to type
- 261
- Tokens
- 80
- Three-star pace
- 100 tpm
At the three-star pace of 100 tokens a minute, this run takes about 48 seconds.
Step 3 of 3 in Positioning & streams, step 11 of 12 in Files & I/O.