Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Do not depend on FileExists() when opening save files for writing #7696

Merged
merged 1 commit into from
Feb 2, 2025
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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
Loading