Looking at code at stackoverflow or elsewhere, it seems I rarely see perror() being used to report the exact nature of an error. printf is much more common. Is this an indicator that there's something wrong or missing with perror? I'd expect it to be used much more often given that it gives better information.
I personally prefer strerror()
which does roughly the same thing, but allows you to use the error message together with a printf or similar function that gives further useful [to the coder or user of the program, depending on the type of error].
For example:
errno = 0;
FILE *f = fopen(argv[1], "rb");
if (!f)
{
fprintf(stderr, "File %s open failed: error code %d ('%s')\n",
argv[1], errno, strerror(errno));
exit(1);
}
That way, we also know WHICH file (say it's a program that copies a file, perror wouldn't necessarily tell you if it was the "source" or "destionation").
If the error is for programming errors [or "stuff that aren't expected to go wrong"], you can also do something like this:
#define UNEXPECTED(cond) do { if (cond) { do_unexpected(errno, #cond, __FILE__, __LINE__); } while(0)
void do_unexpected(int err, const char* cond, const char *file, int line)
{
fprintf(stderr, "Unexpected error %s [errno=%d, errstr=%s] at %s:%d",
cond, err, strerror(errno), file, line);
exit(1);
}
errno = 0;
FILE *config = fopen("config.txt", "r");
UNEXPECTED(!config);
...
That's assuming you don't expect the "config.txt" to be removed, as an example [that's pretty bad programming in general, but perhaps there is a valid reason for it...]
perror() wont exactly give you the line number where error happened, while your printf() would help you identify the exact line where it is being printed. So I think it as more helpful in debugging, nothing wrong with perror() that I know of ....
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With