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

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

    Maybe something like this? You catch the errors without making the code too unreadable, and you can do cleanup after the end of the faux loop.

    #define WRITE_ERROR 100
    #define WRITE_OK 0
    
    int do_fwrite(void* ptr, size_t bytes, int fp) {
      if ( fwrite(ptr, bytes, 1, fp) != bytes ) return WRITE_ERROR;
      return WRITE_OK;
    }
    
    int my_func() {
       int errcode = 0;
    
       ...
       do {
         if ( errcode = do_fwrite(&blah, sizeof(blah), fp) ) break;
         ....
         if ( errcode = do_fwrite(&foo, sizeof(foo), fp) ) break;
         ....
         etc
       } while( false );
    
       fclose(fp);
       return errcode;
    }
    

提交回复
热议问题