Be a bit more careful with fwrite.
[dcpomatic.git] / src / lib / util.cc
index 5eba8d73a0f214f07339998c9a6c4543f5f86e2f..595c7e76eb38355bf014c5a05647fea714b8a9a7 100644 (file)
@@ -783,14 +783,31 @@ increment_eyes (Eyes e)
        return EYES_LEFT;
 }
 
+void
+checked_fwrite (void const * ptr, size_t size, FILE* stream, boost::filesystem::path path)
+{
+       size_t N = fwrite (ptr, 1, size, stream);
+       if (N != size) {
+               if (ferror(stream)) {
+                       fclose (stream);
+                       throw FileError (String::compose("fwrite error %1", errno), path);
+               } else {
+                       fclose (stream);
+                       throw FileError ("Unexpected short write", path);
+               }
+       }
+}
+
 void
 checked_fread (void* ptr, size_t size, FILE* stream, boost::filesystem::path path)
 {
        size_t N = fread (ptr, 1, size, stream);
        if (N != size) {
                if (ferror(stream)) {
+                       fclose (stream);
                        throw FileError (String::compose("fread error %1", errno), path);
                } else {
+                       fclose (stream);
                        throw FileError ("Unexpected short read", path);
                }
        }