Add checked_{read,write} from DoM.
authorCarl Hetherington <cth@carlh.net>
Wed, 13 Apr 2022 21:19:17 +0000 (23:19 +0200)
committerCarl Hetherington <cth@carlh.net>
Thu, 5 May 2022 19:46:30 +0000 (21:46 +0200)
src/file.cc
src/file.h

index c80f5e58cdc18f32c3384d1d9dac160018c4b78a..8759c7c176ff131b146aef66ca09ff1b677bc690 100644 (file)
@@ -46,6 +46,7 @@ File::~File()
 
 
 File::File(boost::filesystem::path path, std::string mode)
+       : _path(path)
 {
 #ifdef LIBDCP_WINDOWS
        std::wstring mode_wide(mode.begin(), mode.end());
@@ -105,6 +106,34 @@ File::operator bool() const
 }
 
 
+void
+File::checked_write(void const * ptr, size_t size)
+{
+       size_t N = write(ptr, 1, size);
+       if (N != size) {
+               if (ferror(_file)) {
+                       throw FileError("fwrite error", _path, errno);
+               } else {
+                       throw FileError("Unexpected short write", _path, 0);
+               }
+       }
+}
+
+
+void
+File::checked_read(void* ptr, size_t size)
+{
+       size_t N = read(ptr, 1, size);
+       if (N != size) {
+               if (ferror(_file)) {
+                       throw FileError("fread error %1", _path, errno);
+               } else {
+                       throw FileError("Unexpected short read", _path, 0);
+               }
+       }
+}
+
+
 /** Windows can't "by default" cope with paths longer than 260 characters, so if you pass such a path to
  *  any boost::filesystem method it will fail.  There is a "fix" for this, which is to prepend
  *  the string \\?\ to the path.  This will make it work, so long as:
index 23204349c40e035f729c8d9cb8d6b2c619340d9e..e0564cae438f7231f2f27227cfed4767f38a9880 100644 (file)
@@ -64,12 +64,16 @@ public:
        /** fgets() wrapper */
        char *gets(char *s, int size);
 
+       void checked_write(void const * ptr, size_t size);
+       void checked_read(void* ptr, size_t size);
+
        /** Close the file; it is not necessary to call this as the
         *  destructor will do it if required.
         */
        void close();
 
 private:
+       boost::filesystem::path _path;
        FILE* _file = nullptr;
 };