diff --git a/include/wfslib/file_device.h b/include/wfslib/file_device.h index 8b9180a..99c9391 100644 --- a/include/wfslib/file_device.h +++ b/include/wfslib/file_device.h @@ -20,7 +20,7 @@ class FileDevice : public Device { uint32_t log2_sector_size = 9 /* 512 */, uint32_t sectors_count = 0, bool read_only = true, - bool create = false); + bool open_create = false); void ReadSectors(const std::span& data, uint32_t sector_address, uint32_t sectors_count) override; void WriteSectors(const std::span& data, uint32_t sector_address, uint32_t sectors_count) override; uint32_t SectorsCount() const override { return sectors_count_; } diff --git a/src/file_device.cpp b/src/file_device.cpp index f6589b8..8523411 100644 --- a/src/file_device.cpp +++ b/src/file_device.cpp @@ -14,14 +14,17 @@ FileDevice::FileDevice(const std::string& path, uint32_t log2_sector_size, uint32_t sectors_count, bool read_only, - bool create) + bool open_create) : log2_sector_size_(log2_sector_size), sectors_count_(sectors_count), read_only_(read_only) { - std::ios_base::openmode mode = std::ios::binary; - if (!create) - mode |= std::ios::in; - if (create || !read_only) + std::ios_base::openmode mode = std::ios::binary | std::ios::in; + if (!read_only) mode |= std::ios::out; file_.reset(new std::fstream(path, mode)); + if (file_->fail() && open_create) { + // try to create the file + mode |= std::ios::trunc; + file_.reset(new std::fstream(path, mode)); + } if (file_->fail()) { throw std::runtime_error("FileDevice: Failed to open file"); }