ferror 会进行多次写入吗? [英] Do ferrors carry through multiple writes?

查看:55
本文介绍了ferror 会进行多次写入吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这个例子中的 ferror 是检查两个 fprintf 是否有错误,还是只检查第二个?

Does the ferror in this example check check both fprintfs for error, or just the second one?

FILE * myout;
if ((myout = fopen("Assignment 11.txt", "a")) != NULL)
{
    fprintf(myout, "First print ", str1);  
    fprintf(myout, "Second print", str1);

    if (ferror(myout))
        fprintf(stderr, "Error printing to file!");

    fclose(myout);
}

推荐答案

如果发生错误,除非在您的流上调用 clearerr,否则不会重置它,所以是的,错误发生在两个写入中的任何一个都被记录.

If an error occurs, it won't be reset unless clearerr is called on your stream, so yes, an error occuring on any of both writes is recorded.

来自 ferror 手册页:

函数 ferror() 测试流指向的流的错误指示符,如果设置了则返回非零值.错误指示器只能由 clearerr() 函数重置.

The function ferror() tests the error indicator for the stream pointed to by stream, returning nonzero if it is set. The error indicator can only be reset by the clearerr() function.

但您也可以简单地使用 fprintf 返回码来查看是否有问题:

But you could also simply use fprintf return code to see if something went wrong:

如果遇到输出错误,则返回负值.

If an output error is encountered, a negative value is returned.

(fprintf 手册页)

像这样(感谢乔纳森指出原帖中的错误):

Like this (Thanks Jonathan for pointing out the errors in the original post):

if (fprintf(myout, "First print %s\n", str1)<0) fprintf(stderr, "Error printing to file #1!");
if (fprintf(myout, "Second print %s\n", str1)<0) fprintf(stderr, "Error printing to file #2!");

这篇关于ferror 会进行多次写入吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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