Do ferrors carry through multiple writes?

浪子不回头ぞ 提交于 2019-12-20 06:27:25

问题


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

回答1:


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.

from ferror manual page:

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.

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 manual page)

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!");


来源:https://stackoverflow.com/questions/40876369/do-ferrors-carry-through-multiple-writes

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!