使用 fwrite 返回写入文件的成功元素的数量,方法是:
if (!(fwrite(...))) {
fprintf(stderr, "Failure");
//perror(???) I sometimes see code that says perror here and I don't know
//exactly what this does.
}
这是否检查是否成功写入文件?还有其他需要担心的事情吗?
谢谢。
简而言之,不完全是。fwrite
返回成功写入的元素数;您需要根据您打算编写的元素数量来检查这一点,即您将参数传递给 fwrite 的那些元素。
您所做的检查是否已写入某些元素。
这是perror的参考。
将全局变量 errno 的值解释为字符串并将该字符串打印到 stderr(标准错误输出流,通常是屏幕),可选地在其前面加上 str 中指定的自定义消息。errno 是一个整数变量,其值描述了调用库函数时产生的最后一个错误。perror 产生的错误字符串取决于开发平台和编译器。如果参数 str 不是空指针,则打印 str 后跟冒号 (:) 和空格。然后,无论 str 是否为空指针,都会打印生成的错误描述,后跟换行符 ('\n')。perror 应该在错误产生后立即调用,否则它可以在调用其他函数时被覆盖。
您也可以使用explain_fwrite()
, explain_errno_fwrite
, ... from libexplain
。
手册页解释说:
该函数用于获取系统调用
explain_fwrite
返回的错误的解释。fwrite(3)
消息将包含的最少是 的值strerror(errno)
,但通常它会做得更好,并更详细地指出根本原因。errno 全局变量将用于获取要解码的错误值。
此函数旨在以类似于以下示例的方式使用(这里的手册页是错误的,正如@puchu在下面的评论中正确指出的那样。我更正了代码以解决该问题):
if (fwrite(ptr, size, nmemb, fp) < nmemb) { fprintf(stderr, "%s\n", explain_fwrite(ptr, size, nmemb, fp)); exit(EXIT_FAILURE); }
警告:此方法不是线程安全的。
您的代码可能无法正确检查错误。采用
if (fwrite(ptr, size, num, f) != num) {
// An error occurred, handle it somehow
}
来自 fwrite 的 Linux 手册页
fread() 和 fwrite() 返回成功读取或写入的项目数(即,不是字符数)。如果发生错误或到达文件结尾,则返回值是一个短项目计数(或零)。
所以你需要与预期的返回值进行比较。
在许多情况下,您可能需要检查 errno
等于EAGAIN
或EINTR
,在这种情况下,您通常希望重试写入请求,而在其他情况下,您希望优雅地处理短写入。
对于 fwrite,在短写入时(写入的数据少于您的全部数据),您可以检查 feof() 和/或 ferror() 以查看流是否正在返回和文件结尾,EOF,例如是否是 PIPE已关闭,或者流是否设置了错误诱导标志。
STRERROR(3) FreeBSD Library Functions Manual STRERROR(3)
NAME
perror, strerror, strerror_r, sys_errlist, sys_nerr — system error mes‐
sages
LIBRARY
Standard C Library (libc, -lc)
SYNOPSIS
#include <stdio.h>
void
perror(const char *string);
...
DESCRIPTION
...
The perror() function finds the error message corresponding to the cur‐
rent value of the global variable errno (intro(2)) and writes it, fol‐
lowed by a newline, to the standard error file descriptor. If the argu‐
ment string is non‐NULL and does not point to the null character, this
string is prepended to the message string and separated from it by a
colon and space (“: ”); otherwise, only the error message string is
printed.
...
STANDARDS
The perror() and strerror() functions conform to ISO/IEC 9899:1999
(“ISO C99”). ...