Why does printf return a value?

2020-02-06 05:44发布

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 somehow depends on the printf status. But I could not think of a scenario where this return value is useful. I, for one, have never checked the return value of printf function.

What are the scenarios where return status from printf is useful?

标签: c printf
6条回答
够拽才男人
2楼-- · 2020-02-06 05:52

in some cases, printf is only able to put a part of your string into stdout, and this is not an error.

if you have to be sure that your string is sended complete, you could use the return value to see this.

its mos useful when working with fprintf and sockets, etc. but still could be useful.

查看更多
够拽才男人
3楼-- · 2020-02-06 06:04

There are at least 2 uses of the return value of printf:

  1. 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.

  2. 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.

查看更多
孤傲高冷的网名
4楼-- · 2020-02-06 06:10

One of the main reasons why this is used is for troubleshooting. Printf can be used to also write to a file (not only STDOUT). Ensuring that all the charachters have been writen to the file is crucial in some applications. An example of this can be found below:

#include <stdio.h>
#include <stdlib.h>

int main(void)
{
  FILE *fp;

  printf("This will display on the screen.\n");

  if((fp=freopen("OUT", "w" ,stdout))==NULL) {
    printf("Cannot open file.\n");
    exit(1);
  }

  if( printf("This will be written to the file OUT.") < 0){
      return -1;
  }

  fclose(fp);

  return 0;
}

You might ask why you should use printf to print a file. Consider this. Some software was developed that had no error logging implemented but instead used printf. A knowledgeable C programmer can redirect the output of printf to a file at the top of the code and thus implement error logging to a file instead of STDOUT. At this point he can use the return value of printf to ensure that the these errors were printed correctly.

查看更多
贼婆χ
5楼-- · 2020-02-06 06:11

There are a couple of situations in which you might want to check the return value of printf. One is to check for errors, as you mention; while there's usually nothing you can do if there's an error on printf, you may, if you're printing something really big, and get an error, decide to try printing it in smaller chunks.

You may also be interested in how wide the output was; printf() returns the number of characters written on success. If you are trying to line up output, and you do a printf() with something of variable width, you can check the return value to find out how many characters were printed, so you know what column you are on. Of course, this only works if all of your characters are 1 column wide (which is true of most ASCII characters), but there are some cases in which this might be useful.

snprintf() prints to a fixed-size buffer instead of stdout or a file. It will only print up to the size of the buffer that you give it; but it's possible that it would require more space to print the full string. It returns the amount of space it would have needed to print the full string; this way, you can use the return value to allocate a new buffer of the appropriate size, and try again, if your original buffer was too small. You almost always use the return value of snprintf(), for this reason.

查看更多
我欲成王,谁敢阻挡
6楼-- · 2020-02-06 06:13

I, too have never used the return value. But beside the error check, you might count the number of characters which have been output, to make some sort of statistic, or limitation

查看更多
SAY GOODBYE
7楼-- · 2020-02-06 06:15

It is mostly for the purposes of error checking. You can make sure that the operation was successful or not using the return value.

If a non-negative value is returned (indicating the number of characters written) it means the operation was successful. If a negative number is returned there was some error.

For example,

#include <stdio.h>
#include <stdlib.h>

int main(void)
{
    int result = printf("This is a test!");
    if (result > 0)
    {
        printf("%d characters were written!", result);
        return EXIT_SUCCESS;
    }
    else return EXIT_FAILURE;
}
查看更多
登录 后发表回答