1
0
Fork 0
mirror of https://github.com/luanti-org/luanti.git synced 2025-06-27 16:36:03 +00:00
luanti/src/client/filecache.cpp

89 lines
1.8 KiB
C++
Raw Normal View History

// Luanti
// SPDX-License-Identifier: LGPL-2.1-or-later
// Copyright (C) 2013 celeron55, Perttu Ahola <celeron55@gmail.com>
// Copyright (C) 2013 Jonathan Neuschäfer <j.neuschaefer@gmx.net>
2012-02-08 11:49:24 +01:00
#include "filecache.h"
2012-02-08 11:49:24 +01:00
#include "log.h"
#include "filesys.h"
#include <string>
#include <iostream>
#include <fstream>
#include <cstdlib>
2012-02-08 11:49:24 +01:00
2024-01-20 16:26:05 +01:00
void FileCache::createDir()
{
if (!fs::CreateAllDirs(m_dir)) {
errorstream << "Could not create cache directory: "
<< m_dir << std::endl;
}
}
2012-03-25 11:50:29 +03:00
bool FileCache::loadByPath(const std::string &path, std::ostream &os)
2012-02-08 11:49:24 +01:00
{
auto fis = open_ifstream(path.c_str(), false);
if (!fis.good())
2012-02-08 11:49:24 +01:00
return false;
bool bad = false;
for(;;){
2024-01-20 16:26:05 +01:00
char buf[4096];
fis.read(buf, sizeof(buf));
2012-02-08 11:49:24 +01:00
std::streamsize len = fis.gcount();
os.write(buf, len);
if(fis.eof())
break;
if(!fis.good()){
bad = true;
break;
}
}
if(bad){
2012-03-25 11:50:29 +03:00
errorstream<<"FileCache: Failed to read file from cache: \""
<<path<<"\""<<std::endl;
2012-02-08 11:49:24 +01:00
}
return !bad;
}
bool FileCache::updateByPath(const std::string &path, std::string_view data)
2012-02-08 11:49:24 +01:00
{
2024-01-20 16:26:05 +01:00
createDir();
2012-02-08 11:49:24 +01:00
auto file = open_ofstream(path.c_str(), true);
if (!file.good())
2012-02-08 11:49:24 +01:00
return false;
file << data;
2012-02-08 11:49:24 +01:00
file.close();
return !file.fail();
}
bool FileCache::update(const std::string &name, std::string_view data)
2012-02-08 11:49:24 +01:00
{
std::string path = m_dir + DIR_DELIM + name;
2012-03-25 11:50:29 +03:00
return updateByPath(path, data);
2012-02-08 11:49:24 +01:00
}
bool FileCache::load(const std::string &name, std::ostream &os)
2012-02-08 11:49:24 +01:00
{
std::string path = m_dir + DIR_DELIM + name;
2012-03-25 11:50:29 +03:00
return loadByPath(path, os);
2012-02-08 11:49:24 +01:00
}
bool FileCache::exists(const std::string &name)
{
std::string path = m_dir + DIR_DELIM + name;
return fs::PathExists(path);
}
2024-01-20 16:26:05 +01:00
bool FileCache::updateCopyFile(const std::string &name, const std::string &src_path)
{
std::string path = m_dir + DIR_DELIM + name;
createDir();
return fs::CopyFileContents(src_path, path);
}