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?
The fprintf() , printf() , and sprintf() functions return the number of characters output, or a negative value if an output error occurs. The ending null character is not counted.
1) Return type and value of printf function h, it is used to display messages as well as values on the standard output device (monitor). printf returns an integer value, which is the total number of printed characters. For example: if you are printing "Hello" using printf, printf will return 5.
printf() - printf() returns the number of characters successfully written on the output. It is used to simply print data in the output. scanf() - It returns the number of data items that have been entered successfully.
printf() returns total no. of character printed on console, you pass 1000; so first inner printf() function will work and print 1000,and here no. of character is 4.
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.
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