diff --git a/Storage/Disk/Formats/AcornADF.cpp b/Storage/Disk/Formats/AcornADF.cpp index 28b319067..1568fbb86 100644 --- a/Storage/Disk/Formats/AcornADF.cpp +++ b/Storage/Disk/Formats/AcornADF.cpp @@ -111,6 +111,8 @@ void AcornADF::store_updated_track_at_position(unsigned int head, unsigned int p } std::lock_guard lock_guard(file_access_mutex); - fseek(file_, get_file_offset_for_position(head, position), SEEK_SET); + long file_offset = get_file_offset_for_position(head, position); + ensure_file_is_at_least_length(file_offset); + fseek(file_, file_offset, SEEK_SET); fwrite(parsed_track.data(), 1, parsed_track.size(), file_); } diff --git a/Storage/Disk/Formats/SSD.cpp b/Storage/Disk/Formats/SSD.cpp index b91c7dcbd..0c7f23984 100644 --- a/Storage/Disk/Formats/SSD.cpp +++ b/Storage/Disk/Formats/SSD.cpp @@ -106,6 +106,8 @@ void SSD::store_updated_track_at_position(unsigned int head, unsigned int positi } std::lock_guard lock_guard(file_access_mutex); - fseek(file_, get_file_offset_for_position(head, position), SEEK_SET); + long file_offset = get_file_offset_for_position(head, position); + ensure_file_is_at_least_length(file_offset); + fseek(file_, file_offset, SEEK_SET); fwrite(parsed_track.data(), 1, parsed_track.size(), file_); } diff --git a/Storage/FileHolder.cpp b/Storage/FileHolder.cpp index 6271a79cd..1395da998 100644 --- a/Storage/FileHolder.cpp +++ b/Storage/FileHolder.cpp @@ -85,3 +85,16 @@ uint16_t FileHolder::fgetc16be() return result; } + +void FileHolder::ensure_file_is_at_least_length(long length) +{ + fseek(file_, 0, SEEK_END); + long bytes_to_write = length - ftell(file_); + if(bytes_to_write > 0) + { + uint8_t *empty = new uint8_t[bytes_to_write]; + memset(empty, 0, bytes_to_write); + fwrite(empty, sizeof(uint8_t), (size_t)bytes_to_write, file_); + delete[] empty; + } +} diff --git a/Storage/FileHolder.hpp b/Storage/FileHolder.hpp index bf1029102..458927608 100644 --- a/Storage/FileHolder.hpp +++ b/Storage/FileHolder.hpp @@ -65,6 +65,12 @@ class FileHolder { */ uint16_t fgetc16be(); + /*! + Ensures the file is at least @c length bytes long, appending 0s until it is + if necessary. + */ + void ensure_file_is_at_least_length(long length); + FILE *file_; struct stat file_stats_; bool is_read_only_;