简体   繁体   English

检查 printf 的返回值重要吗?

[英]Is checking the return value of printf important?

In one of my University Projects, I got points off and feedback from my professor saying I didn't handle printf errors.在我的一个大学项目中,我从教授那里得到了分数和反馈,说我没有处理printf错误。

In English --> / * ### FB: Error handling printf () is missing * /英文--> / * ### 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?我的问题是,始终检查printf函数的返回值并处理错误真的很重要吗? 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.即使我发现错误,我仍然会使用fprintf打印到stderr ,为此我必须再次检查fprintf的返回类型。

So when should the return value be checked, and how should it be handled?那么什么时候应该检查返回值,又应该如何处理呢?

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.然而,在printf的情况下,在大多数情况下这样做几乎没有用。 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.正如你提到的,如果它失败,你可以使用fprintf打印到stderr ,但那么加薪的应该对错误进行检查的问题。

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.如果您不重定向或重新打开stderr您可能会遇到同样的问题,在这种情况下,这可能无关紧要,但如果stderr指向其他地方,则在那里写入可能有价值。 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.我在写入日志文件以确定何时滚动日志时使用fprintf完成了此操作,但是由于printf通常写入交互式控制台(如果不是由于重定向,您将不会知道),那不会真的适用。

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.这是一件好事,但是像大多数规则一样,也有例外,这就是其中之一。

For clarity - printf() returns ...为清楚起见 - printf()返回 ...

The printf function returns the number of characters transmitted, or a negative value if an output or encoding error occurred. printf函数返回传输的字符数,如果发生输出或编码错误,则返回负值。 C11 §7.21.6.3 3 C11 §7.21.6.3 3


Checking the return value of printf() for a negative value is pedantic , and is not usually needed.检查printf()的返回值是否为负值是迂腐的,通常不需要。 One could consider the following cases:可以考虑以下几种情况:


Environmental limits .环境限制

A single printf() with "%s" may exceed an environmental limit and cause printf() to return a negative value.带有"%s"的单个printf()可能会超出环境限制并导致printf()返回负值。 This would not imply the a subsequent message on fprintf(stderr, ... must also fail.这并不意味着fprintf(stderr, ...上的后续消息也必须失败。

The number of characters that can be produced by any single conversion shall be at least 4095. C11 §7.21.6.1 15任何单个转换可以产生的字符数至少应为 4095。 C11 §7.21.6.1 15


Weak output devices .弱输出设备

A case where stdout is known to be often re-directed over a communication interface where output failures need to be detected.已知stdout通常通过需要检测输出故障的通信接口重定向的情况。 Even though a screen output has extraordinary high success, this is not so with various others output streams like serial (rs232).尽管屏幕输出非常成功,但对于串行(rs232)等各种其他输出流而言,情况并非如此。 In this case stdout and stderr may re-direct differently and so stderr may remain reliable.在这种情况下, stdoutstderr可能会以不同的方式stderr ,因此stderr可能保持可靠。


In any case, if the professor grades on a curve, likely many incurred the same minus point - so no grade difference.在任何情况下,如果教授在曲线上打分,很可能很多人都得到了相同的负分——所以没有成绩差异。 Get use to customers with odd requirements and expectations.习惯于有奇怪要求和期望的客户。

Not checking a return value is considered bad practice.不检查返回值被认为是不好的做法。 BUT it is considered clean, if you explicitly state that you ignore the return value by adding (void) in front of the function call:但它被认为是干净的,如果你明确声明你通过在函数调用前添加(void)来忽略返回值:

(void) printf(...);

This indicates, that you know there is return value, but you are intentionally ignoring it.这表明,您知道有返回值,但您故意忽略它。

The Unix philosophy is that stdout (though not necessarily stderr ) should be further processable. Unix 哲学是stdout (虽然不一定是stderr )应该可以进一步处理。 Compilers and generators use it for code output.编译器和生成器将它用于代码输出。 stdout should be where your process's product goes. stdout应该是您的流程产品所在的位置。 If that product is cut short, your processes shouldn't be returning EXIT_SUCCESS .如果该产品被缩短,您的流程不应返回EXIT_SUCCESS I say do check those writes to stdout .我说一定要检查那些对stdout写入。

( stderr , on the other hand, is more or less for convenience. If you're using it, you're probably in a state of error already anyway, and if your error reporting fails, there's not much you can do (though you should still signal the error with return codes).) (另一方面, stderr或多或少是为了方便起见。如果您正在使用它,那么无论如何您可能已经处于错误状态,并且如果您的错误报告失败,则您无能为力(尽管您仍应使用返回码发出错误信号)。)

No. In the real world, as opposed to an academic exercise in a culture mit einem Ruf für Pedanterie , it's not important to check the return value of printf() , or close() , or quite a few other things.不。在现实世界中,与文化mit einem Ruf für Pedanterie 中的学术练习相反,检查printf()close()或其他很多东西的返回值并不重要。 If there's no reasonable way to act on a piece of information, why bother collecting it?如果没有合理的方法来处理一条信息,为什么还要收集它呢?

If you are writing an app that spits JSON (for example: read from DB export the data into stdout ) the caller of your program might redirect the output into a file.如果您正在编写一个输出 JSON 的应用程序(例如:从 DB 读取数据,将数据导出到stdout ),您的程序调用者可能会将输出重定向到一个文件中。 In such case - the disk might get filled.在这种情况下 - 磁盘可能会被填满。

Question: who will complain about the disk being full: the shell or your program?问题:谁会抱怨磁盘已满:shell 还是您的程序?

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

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