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

前端 未结 13 1299
梦如初夏
梦如初夏 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 11:59

    A potentially elegant C solution for this could be something like this (warning - untested, uncompiled code ahead):

    
      size_t written;
      int    ok = 1;
      size_t num_elements = x;
      ok = (fwrite(stuff, sizeof(data), num_elements, outfile) == num_elements);
    
      if (ok) {
        ... do other stuff ...
      }
    
      ok = ok && (fwrite(stuff, sizeof(data), num_elements, outfile) == num_elements);
    
      if (ok) {
        ... etc etc ad nauseam ...
      }
    
      fclose(outfile);
    
      return ok;
    
    

    The above accomplishes two goals at the same time:

    • Return values are checked, thus eliminating the warning and giving you the ability to return a status code.
    • Thanks to the short circuit evaluation, should one of the fwrite() calls fail, the subsequent ones will not be executed, so at least the file write stops instead of giving you a potentially corrupt file if the error condition disappears halfway through the function and you're able to write data again

    Unfortunately the 'ugly' if (ok) blocks are necessary if you don't want to use the short-circuit evaluation everywhere. I've seen this pattern used in comparatively small functions using short circuit evaluation everywhere and I would think that it's probably best suited to that particular use.

提交回复
热议问题