C语言 在 C 中检查 fwrite 是否成功,perror
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2329842/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Checking for success of fwrite in C, perror
提问by Crystal
With fwrite returning the number of successful elements written to the file, by saying:
使用 fwrite 返回写入文件的成功元素数,如下所示:
if (!(fwrite(...))) {
fprintf(stderr, "Failure");
//perror(???) I sometimes see code that says perror here and I don't know
//exactly what this does.
}
Does this check for successful writing to the file? Are there other things to worry about?
这是否检查成功写入文件?还有其他需要担心的事情吗?
Thanks.
谢谢。
回答by
In short, not quite. fwritereturns the number of elements successfully written; you need to check this against the number of elements you intended to write i.e. those you passed in argument to fwrite.
简而言之,不完全是。fwrite返回成功写入的元素数;您需要根据您打算编写的元素数量进行检查,即您将参数传递给 fwrite 的元素数量。
What you've done checks that some elements have been written.
您所做的检查是否已写入某些元素。
Here's a reference for perror.
这是perror的参考。
Interprets the value of the global variable errno into a string and prints that string to stderr (standard error output stream, usually the screen), optionaly preceding it with the custom message specified in str. errno is an integral variable whose value describes the last error produced by a call to a library function. The error strings produced by perror depend on the developing platform and compiler. If the parameter str is not a null pointer, str is printed followed by a colon (:) and a space. Then, whether str was a null pointer or not, the generated error description is printed followed by a newline character ('\n'). perror should be called right after the error was produced, otherwise it can be overwritten in calls to other functions.
将全局变量 errno 的值解释为一个字符串并将该字符串打印到 stderr(标准错误输出流,通常是屏幕),可选地在它前面加上 str 中指定的自定义消息。errno 是一个整数变量,它的值描述了调用库函数产生的最后一个错误。perror 产生的错误字符串取决于开发平台和编译器。如果参数 str 不是空指针,则打印 str 后跟一个冒号 (:) 和一个空格。然后,无论 str 是否为空指针,都会打印生成的错误描述,后跟换行符 ('\n')。perror 应该在错误产生后立即调用,否则它可以在调用其他函数时被覆盖。
回答by M.S. Dousti
You can also use explain_fwrite(), explain_errno_fwrite, ... from libexplain.
您也可以使用explain_fwrite(), explain_errno_fwrite, ... from libexplain。
The man pageexplains:
该手册页说明:
The
explain_fwritefunction is used to obtain an explanation of an error returned by thefwrite(3)system call. The least the message will contain is the value ofstrerror(errno), but usually it will do much better, and indicate the underlying cause in more detail.The errno global variable will be used to obtain the error value to be decoded.
This function is intended to be used in a fashion similar to the following example (the man-page was wrong here, as correctly pointed out by @puchuin the comment below. I corrected the code to address the issue):
if (fwrite(ptr, size, nmemb, fp) < nmemb) { fprintf(stderr, "%s\n", explain_fwrite(ptr, size, nmemb, fp)); exit(EXIT_FAILURE); }
该
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); }
Caveat:This method is not thread-safe.
警告:此方法不是线程安全的。
回答by Tronic
Your code might not check for errors properly. Use
您的代码可能无法正确检查错误。用
if (fwrite(ptr, size, num, f) != num) {
// An error occurred, handle it somehow
}
回答by mctylr
From the Linux man page of fwrite
来自 fwrite 的 Linux 手册页
fread() and fwrite() return the number of items successfully read or written (i.e., not the number of characters). If an error occurs, or the end-of-file is reached, the return value is a short item count (or zero).
fread() 和 fwrite() 返回成功读取或写入的项目数(即,不是字符数)。如果发生错误或到达文件末尾,则返回值是一个短项目计数(或零)。
so you need to compare with what is expected return value.
所以你需要与预期的返回值进行比较。
In many cases you may need to check for errnoequal to EAGAINor EINTR, in which case you normally want to retry the write request, while in other cases you want to handle short writes gracefully.
在许多情况下,您可能需要检查errnoequal toEAGAIN或EINTR,在这种情况下,您通常希望重试写入请求,而在其他情况下,您希望优雅地处理短写入。
For fwrite, on a short write(where less than your entire data was written) you can check feof() and/or ferror() to see if the stream is returning and end-of-file, EOF, such as if a PIPE was closed, or if the stream has its error inducator flag set.
对于 fwrite,在短写入时(写入的数据少于整个数据),您可以检查 feof() 和/或 ferror() 以查看流是否正在返回和文件结尾,EOF,例如 PIPE已关闭,或者流是否设置了错误指示符标志。
回答by just somebody
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”). ...

