What is a good programming pattern for handling return values from stdio file writing functions

前端 未结 13 1248
梦如初夏
梦如初夏 2021-01-02 11:28

I\'m working on some code that generates a lot of

ignoring return value of ‘size_t fwrite(const void*, size_t, size_t, FILE*)’, declared with attribute warn         


        
13条回答
  •  既然无缘
    2021-01-02 12:02

    I'd do something along these lines:

    FILE * file = fopen("foo", "wb");
    if(!file) return FAILURE;
    
    // assume failure by default
    _Bool success = 0;
    
    do
    {
        if(!fwrite(&bar, sizeof(bar), 1, file))
            break;
    
        // [...]
    
        if(!fwrite(&baz, sizeof(baz), 1, file))
            break;
    
        // [...]
    
        success = 1;
    } while(0);
    
    fclose(file);
    
    return success ? SUCCESS : FAILURE;
    

    With a little C99 macro magic

    #define with(SUBJECT, FINALIZE, ...) do { \
        if(SUBJECT) do { __VA_ARGS__ } while(0); if(SUBJECT) FINALIZE; \
    } while(0)
    

    and using ferror() instead of our own error flag as suggested by Jonathan Leffler, this can be written as

    FILE * file = fopen("foo", "wb");
    with(file, fclose(file),
    {
        if(!fwrite(&bar, sizeof(bar), 1, file))
            break;
    
        // [...]
    
        if(!fwrite(&baz, sizeof(baz), 1, file))
            break;
    
        // [...]
    });
    
    return file && !ferror(file) ? SUCCESS : FAILURE;
    

    If there are other error conditions aside from io errors, you'll still have to track them with one or more error variables, though.

    Also, your check against sizeof(blah) is wrong: fwrite() returns the count of objects written!

提交回复
热议问题