检查C中的fwrite是否成功,perror

时间:2010-02-24 21:49:35

标签: c fwrite

使用fwrite返回写入文件的成功元素的数量,说:

if (!(fwrite(...))) {
    fprintf(stderr, "Failure");
    //perror(???)  I sometimes see code that says perror here and I don't know 
    //exactly what this does.
}

这是否检查成功写入文件?还有其他需要担心的事情吗?

感谢。

5 个答案:

答案 0 :(得分:12)

总之,不完全。 fwrite返回成功写入的元素数;你需要根据你想写的元素数来检查这一点,即你在fwrite参数中传递的元素。

您所做的工作会检查是否已写入某些元素。

以下是perror的参考资料。

  

解释全局的价值   变量errno变成一个字符串和   将该字符串打印到stderr(标准   错误输出流,通常是   屏幕),可选地在它之前   str中指定的自定义消息。   errno是一个不可变的变量   value描述最后一个错误   通过调用图书馆产生的   功能。生成错误字符串   perror取决于发展   平台和编译器。如果   参数str不是空指针,   str打印后跟冒号(:)   和一个空间。然后,str是否是a   空指针与否,生成   随后打印错误描述   用换行符('\ n')。 PERROR   应在错误发生后立即调用   是生产,否则它可以   在打电话给其他人时被覆盖   功能

答案 1 :(得分:2)

您的代码可能无法正确检查错误。使用

if (fwrite(ptr, size, num, f) != num) {
    // An error occurred, handle it somehow
}

答案 2 :(得分:2)

您还可以使用explain_fwrite()中的explain_errno_fwritelibexplain,...。

man page解释:

  

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

注意::该方法不是线程安全的。

答案 3 :(得分:0)

来自fwrite的Linux手册页

  

fread()和fwrite()返回成功读取的项目数或   书面(即不是字符数)。如果发生错误,或   达到文件结尾,返回值是一个短项目计数(或   零)。

因此您需要与预期的回报值进行比较。

在许多情况下,您可能需要检查等待errnoEAGAIN的{​​{1}},在这种情况下,您通常需要重试写入请求,而在其他情况下你想优雅地处理短写。

对于fwrite,在短写(其中写入的数据少于整个数据)中,您可以检查feof()和/或ferror()以查看流是否正在返回和结束-file,EOF,例如PIPE是否关闭,或者流是否设置了错误inducator标志。

答案 4 :(得分:0)

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”).  ...