简体   繁体   English

为什么printf会返回一个值?

[英]Why does printf return a value?

I know that printf returns a negative error or number of characters printed on success. 我知道printf返回一个负面错误或成功打印的字符数。 Only reason to check this return value is if the execution of program somehow depends on the printf status. 只检查此返回值的唯一原因是程序的执行以某种方式取决于printf状态。 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. 我,从来没有检查过printf函数的返回值。

What are the scenarios where return status from printf is useful? printf返回状态有用的场景是什么?

There are at least 2 uses of the return value of printf : printf的返回值至少有2次使用:

  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. 当您的输出是交互式或纯信息时,这很少重要,但对于从stdio或文件处理文本并将结果写入stdout的程序,重要的是要知道是否有错误(例如磁盘已满,关闭管道或丢弃)网络连接)阻止了整个输出的写入。 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. 但是,由于缓冲,检查printf本身的结果通常没有帮助。 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. 在写完最后一个输出并进行刷新后,您需要检查ferror(stdout) ,以便可靠地指示是否发生了写入错误。 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; 在另一方面,检查返回值printf允许您检测故障 ,所以你不要浪费时间试图在第一线已经没有写百万行的,所以它可以是一个非常有用的检查; 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. 例如,如果您的字段是80个字节而printf返回52,那么您需要再写28个填充字节来完成该字段。

There are a couple of situations in which you might want to check the return value of printf. 在某些情况下,您可能需要检查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. 虽然如果printf上有错误,通常没有什么可以做的,如果你打印的东西真的很大,并且得到错误,你可以决定尝试用较小的块打印它。

You may also be interested in how wide the output was; 您可能还对输出的宽度感兴趣; printf() returns the number of characters written on success. printf()返回成功写入的字符数。 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. 如果你试图排列输出,并且你使用宽度可变的printf() ,你可以检查返回值以找出打印的字符数,这样你就可以知道你所在的列。 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. 当然,这仅适用于所有字符都是1列宽(大多数ASCII字符都适用)的情况,但在某些情况下这可能会有用。

snprintf() prints to a fixed-size buffer instead of stdout or a file. snprintf()打印到固定大小的缓冲区而不是stdout或文件。 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. 因此,您几乎总是使用snprintf()的返回值。

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). Printf也可用于写入文件(不仅仅是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. 您可能会问为什么要使用printf来打印文件。 Consider this. 考虑一下。 Some software was developed that had no error logging implemented but instead used printf. 开发了一些没有实现错误记录但是使用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. 知识渊博的C程序员可以将printf的输出重定向到代码顶部的文件,从而实现错误记录到文件而不是STDOUT。 At this point he can use the return value of printf to ensure that the these errors were printed correctly. 此时,他可以使用printf的返回值来确保正确打印这些错误。

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;
}

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 但是除了错误检查之外,您可以计算已输出的字符数,以进行某种统计或限制

in some cases, printf is only able to put a part of your string into stdout, and this is not an error. 在某些情况下, printf只能将一部分字符串放入stdout,这不是错误。

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. 它在使用fprintf和插座等时很有用,但仍然有用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM