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

前端 未结 13 1195
梦如初夏
梦如初夏 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:00

    The poor man's C exception handling based on goto (in fact, the one and only instance of goto NOT being harmful):

    int foo() {
        FILE * fp = fopen(...);
        ....
    
        /* Note: fwrite returns the number of elements written, not bytes! */
        if (fwrite (&blah, sizeof (blah), 1, fp) != 1) goto error1;
    
        ...
    
        if (fwrite (&foo, sizeof (foo), 1, fp) != 1) goto error2;
    
        ...
    
    ok:
        /* Everything went fine */
        fclose(fp);
        return 0;
    
    error1:
        /* Error case 1 */
        fclose(fp);
        return -1;
    
    error2:
        /* Error case 2 */
        fclose(fp);
        return -2;
    }
    

    You get the idea. Restructure as you wish (single/multiple returns, single cleanup, custom error messages, etc.). From my experience this is the most common C error handling pattern out there. The crucial point is: NEVER, EVER ignore stdlib return codes, and any good reason to do so (e.g. readability) is not good enough.

提交回复
热议问题