In one of my University Projects, I got points off and feedback from my professor saying I didn't handle printf
errors.
In English --> / * ### FB: Error handling printf () is missing * /
/* ### FB: Fehlerbehandlung printf() fehlt */
printf("%7lu %8lld %10s %3lu %-8s %-8s %8lu %12s %s %s %s\n",
sb->st_ino, nblks, permstr, (unsigned long) sb->st_nlink,
username, groupname, sb->st_size,
ntime, filename, (symlink ? "->" : ""),
(symlink ? symlink : "")
);
My question is, is it really important to always check return value of the printf
function and handle the errors? Even if I find an error I will still use fprintf
to print to stderr
, for which I have to check the return type for fprintf
again.
So when should the return value be checked, and how should it be handled?
Generally speaking, you should always check the return value of a function for errors.
In the case of printf
however, there is little use in doing so in most cases. As you mentioned, if it does fail you could use fprintf
to print to stderr
, but then that raises the question of should that be checked for error.
If you don't redirect or reopen stderr
you'll likely have the same issue, in which case it probably doesn't matter, but if stderr
is pointing someplace else then writing there could have value. You could also exit the process but you need to determine if it makes sense to do so.
One notable time you might want to check the return value is if you want to keep track of how many characters you printed for formatting purposes. I've done this with fprintf
when writing to a log file to determine when to roll the log, but since printf
generally writes to an interactive console (and if it's not due to redirection, you wouldn't know it), that wouldn't really apply.
As for your professor, my only guess is that he wants you to get into the habit of checking for errors. That is a Good Thing, however like most rules there are exceptions, and this is one of them.