Skip to content

Commit

Permalink
Do not depend on FileExists() when opening save files for writing
Browse files Browse the repository at this point in the history
  • Loading branch information
StephenCWills authored and AJenbo committed Feb 2, 2025
1 parent a4f38d5 commit d9dc491
Showing 1 changed file with 5 additions and 4 deletions.
9 changes: 5 additions & 4 deletions Source/mpq/mpq_writer.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -91,9 +91,9 @@ MpqWriter::MpqWriter(const char *path)
const std::string dir = std::string(Dirname(path));
RecursivelyCreateDir(dir.c_str());
LogVerbose("Opening {}", path);
bool isNewFile = false;
std::string error;
bool exists = FileExists(path);
if (!exists) {
if (!FileExists(path)) {
// FileExists() may return false in the case of an error
// so we use "ab" instead of "wb" to avoid accidentally
// truncating an existing file
Expand All @@ -112,6 +112,7 @@ MpqWriter::MpqWriter(const char *path)
goto on_error;
}
size_ = static_cast<uint32_t>(fileSize);
isNewFile = size_ == 0;
LogVerbose("GetFileSize(\"{}\") = {}", path, size_);

if (!stream_.Open(path, "r+b")) {
Expand All @@ -124,7 +125,7 @@ MpqWriter::MpqWriter(const char *path)

if (blockTable_ == nullptr || hashTable_ == nullptr) {
MpqFileHeader fhdr;
if (!exists) {
if (isNewFile) {
InitDefaultMpqHeader(&fhdr);
} else if (!ReadMPQHeader(&fhdr)) {
error = "Failed to read MPQ header";
Expand Down Expand Up @@ -162,7 +163,7 @@ MpqWriter::MpqWriter(const char *path)

// Write garbage header and tables because some platforms cannot `Seekp` beyond EOF.
// The data is incorrect at this point, it will be overwritten on Close.
if (!exists)
if (isNewFile)
WriteHeaderAndTables();
#endif
}
Expand Down

0 comments on commit d9dc491

Please sign in to comment.