iw4x-client/src/Utils/IO.cpp

122 lines
2.4 KiB
C++
Raw Normal View History

2022-02-27 07:53:44 -05:00
#include <STDInclude.hpp>
2017-01-19 16:23:59 -05:00
namespace Utils::IO
2017-01-19 16:23:59 -05:00
{
bool FileExists(const std::string& file)
2017-01-19 16:23:59 -05:00
{
//return std::ifstream(file).good();
return GetFileAttributesA(file.data()) != INVALID_FILE_ATTRIBUTES;
}
bool WriteFile(const std::string& file, const std::string& data, bool append)
{
const auto pos = file.find_last_of("/\\");
if (pos != std::string::npos)
2017-01-19 16:23:59 -05:00
{
CreateDir(file.substr(0, pos));
2017-01-19 16:23:59 -05:00
}
std::ofstream stream(file, std::ios::binary | std::ofstream::out | (append ? std::ofstream::app : std::ofstream::out));
if (stream.is_open())
2017-01-19 16:23:59 -05:00
{
stream.write(data.data(), static_cast<std::streamsize>(data.size()));
stream.close();
return true;
}
return false;
}
std::string ReadFile(const std::string& file)
{
std::string data;
ReadFile(file, &data);
return data;
}
bool ReadFile(const std::string& file, std::string* data)
{
if (!data) return false;
data->clear();
if (FileExists(file))
{
std::ifstream stream(file, std::ios::binary);
if (!stream.is_open()) return false;
2017-01-19 16:23:59 -05:00
stream.seekg(0, std::ios::end);
std::streamsize size = stream.tellg();
stream.seekg(0, std::ios::beg);
2017-01-19 16:23:59 -05:00
if (size > -1)
2017-01-19 16:23:59 -05:00
{
data->resize(static_cast<uint32_t>(size));
stream.read(data->data(), size);
2017-01-19 16:23:59 -05:00
stream.close();
2017-02-10 09:18:11 -05:00
return true;
2017-01-19 16:23:59 -05:00
}
}
return false;
}
2017-02-10 09:18:11 -05:00
bool RemoveFile(const std::string& file)
{
return DeleteFileA(file.data()) == TRUE;
}
std::size_t FileSize(const std::string& file)
{
if (FileExists(file))
2017-02-10 09:18:11 -05:00
{
std::ifstream stream(file, std::ios::binary);
2017-01-19 16:23:59 -05:00
if (stream.good())
2017-01-19 16:23:59 -05:00
{
stream.seekg(0, std::ios::end);
return static_cast<std::size_t>(stream.tellg());
2017-01-19 16:23:59 -05:00
}
}
return 0;
}
bool CreateDir(const std::string& dir)
{
return std::filesystem::create_directories(dir);
}
bool DirectoryExists(const std::filesystem::path& directory)
{
return std::filesystem::is_directory(directory);
}
bool DirectoryIsEmpty(const std::filesystem::path& directory)
{
return std::filesystem::is_empty(directory);
}
2017-01-19 16:23:59 -05:00
2023-01-06 07:51:41 -05:00
std::vector<std::string> ListFiles(const std::filesystem::path& directory, const bool recursive)
{
std::vector<std::string> files;
2023-01-06 07:51:41 -05:00
if (recursive)
{
2023-01-06 07:51:41 -05:00
for (auto& file : std::filesystem::recursive_directory_iterator(directory))
{
files.push_back(file.path().generic_string());
}
}
else
{
for (auto& file : std::filesystem::directory_iterator(directory))
{
files.push_back(file.path().generic_string());
}
}
return files;
2017-01-19 16:23:59 -05:00
}
}