为什么printf的返回值? [英] Why does printf return a value?

查看:132
本文介绍了为什么printf的返回值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道的printf 返回打印成功字符的负误差或数字。唯一的理由来检查这个返回值,如果程序的执行在某种程度上依赖于的printf 状态。但我想不出这样一个场景,这个返回值是有用的。拿我来说,从来没有检查的返回值的printf 功能。

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.

什么是场景中的返回状态的printf 是有用的?

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

推荐答案

有返回值的printf 的至少2个用途:

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


  1. 要检查是否有错误。这是很少重要的,当你的输出是交互或纯粹的信息,但为从标准输入输出或文件处理的文本并将结果写入到stdout的程序,它知道是否错误(如磁盘已满是很重要的,封闭的管道或下降网络连接)prevented被写入整个输出。这是特别重要的,如果源文件将被删除/由输出更换一次的输出就完成了。然而,由于缓冲,检查的printf 的结果本身通常是没有帮助的。你要检查 FERROR(标准输出)写最后的输出,为了得到是否发生了任何错误,写一个可靠的指示后冲洗。在另一方面,检查的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.

如果输出的字符数并不明显,你可能想知道的字符是如何写的。这个数字的天真用法是用于排队列,但假设字符在他们的视觉presentation固定宽度是相当​​陈旧。它可能是有意义的,如果你是格式化源$ C ​​$ C,虽然。另一个类似的用法(不知道这是否是少跌多陈旧的)是写在一个文件中固定宽度的字段。例如,如果你的字段是80个字节,的printf 返回52,你会想要写28个填充字节来完成场外。

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.

这篇关于为什么printf的返回值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆