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

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

    Nesting is bad, and multiple returns are not good either.

    I used to use following pattern:

    #define SUCCESS (0)
    #define FAIL    (-1)
    int ret = SUCCESS;
    
    if (!fwrite(...))
        ret = FAIL;
    if (SUCCESS == ret) {
        do_something;
        do_something_more;
        if (!fwrite(...))
            ret = FAIL;
    }
    if (SUCCESS == ret)
        do_something;
    
    return ret;
    

    I know it looks ugly but it has single return point, no excessive nesting and very easy to maintain.

提交回复
热议问题