I know that printf
returns a negative error or number of characters printed on success. Only reason to check this return value is if the execution of program s
There are at least 2 uses of the return value of printf
:
To check for errors. This is rarely important when your output is interactive or purely informative, but for programs that are processing text from stdio or a file and writing the result to stdout, it's important to know whether an error (such as disk full, closed pipe, or dropped network connection) prevented the entire output from being written. This is especially important if the source file will be deleted/replaced by the output once the output is complete. However, due to buffering, checking the result of printf
itself is usually not helpful. You'll want to check ferror(stdout)
after writing the last output and flushing in order to get a reliable indication of whether any write errors occurred. On the other hand, checking the return value of printf
allows you to detect failure early so you don't waste time attempting to write millions of lines when the first line already failed, so it can be a very useful check; it's just not a sufficient check by itself.
If the number of characters output is not obvious, you may want to know how many characters were written. A naive usage of this number would be for lining up columns, but assuming characters have fixed width in their visual presentation is rather antiquated. It might make sense if you were formatting source code, though. Another similar usage (not sure whether this is less or more antiquated) is writing fixed-width fields in a file. For example, if your fields are 80 bytes and printf
returned 52, you'd want to write 28 more padding bytes to finish off the field.