1
0
mirror of https://github.com/vcmi/vcmi.git synced 2025-06-19 00:17:56 +02:00

Fix and simplify game saving / loading

This commit is contained in:
Ivan Savenko
2025-04-12 21:25:23 +03:00
parent f5f8ed192b
commit 966468f3fa
16 changed files with 128 additions and 213 deletions

View File

@ -14,50 +14,23 @@ VCMI_LIB_NAMESPACE_BEGIN
CSaveFile::CSaveFile(const boost::filesystem::path &fname)
: serializer(this)
, sfile(fname.c_str(), std::ios::out | std::ios::binary)
, fName(fname)
{
openNextFile(fname);
}
sfile.exceptions(std::ifstream::failbit | std::ifstream::badbit); //we throw a lot anyway
//must be instantiated in .cpp file for access to complete types of all member fields
CSaveFile::~CSaveFile() = default;
if(!sfile)
throw std::runtime_error("Error: cannot open file '" + fName.string() + "' for writing!");
sfile.write("VCMI", 4); //write magic identifier
serializer & ESerializationVersion::CURRENT; //write format version
sfile.write(SAVEGAME_MAGIC.c_str(), SAVEGAME_MAGIC.length());
}
int CSaveFile::write(const std::byte * data, unsigned size)
{
sfile->write(reinterpret_cast<const char *>(data), size);
sfile.write(reinterpret_cast<const char *>(data), size);
return size;
}
void CSaveFile::openNextFile(const boost::filesystem::path &fname)
{
fName = fname;
try
{
sfile = std::make_unique<std::fstream>(fname.c_str(), std::ios::out | std::ios::binary);
sfile->exceptions(std::ifstream::failbit | std::ifstream::badbit); //we throw a lot anyway
if(!(*sfile))
THROW_FORMAT("Error: cannot open to write %s!", fname);
sfile->write("VCMI",4); //write magic identifier
serializer & ESerializationVersion::CURRENT; //write format version
}
catch(...)
{
logGlobal->error("Failed to save to %s", fname.string());
clear();
throw;
}
}
void CSaveFile::clear()
{
fName.clear();
sfile = nullptr;
}
void CSaveFile::putMagicBytes(const std::string &text)
{
write(reinterpret_cast<const std::byte*>(text.c_str()), text.length());
}
VCMI_LIB_NAMESPACE_END