iw4x-client/src/Utils/IO.cpp

110 lines
2.1 KiB
C++
Raw Normal View History

2017-01-19 16:23:59 -05:00
#include "STDInclude.hpp"
namespace Utils
{
namespace IO
{
bool FileExists(std::string file)
{
2017-06-02 16:18:00 -04:00
//return std::ifstream(file).good();
return GetFileAttributesA(file.data()) != INVALID_FILE_ATTRIBUTES;
2017-01-19 16:23:59 -05:00
}
2017-02-10 09:18:11 -05:00
bool WriteFile(std::string file, std::string data, bool append)
2017-01-19 16:23:59 -05:00
{
auto pos = file.find_last_of("/\\");
if (pos != std::string::npos)
{
2017-02-10 16:02:13 -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())
{
stream.write(data.data(), data.size());
stream.close();
2017-02-10 09:18:11 -05:00
return true;
2017-01-19 16:23:59 -05:00
}
2017-02-10 09:18:11 -05:00
return false;
2017-01-19 16:23:59 -05:00
}
std::string ReadFile(std::string file)
{
2017-02-10 09:18:11 -05:00
std::string data;
ReadFile(file, &data);
return data;
}
bool ReadFile(std::string file, std::string* data)
{
if (!data) return false;
data->clear();
2017-01-19 16:23:59 -05:00
if (FileExists(file))
{
std::ifstream stream(file, std::ios::binary);
2017-02-10 09:18:11 -05:00
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();
2017-01-19 16:23:59 -05:00
stream.seekg(0, std::ios::beg);
if (size > -1)
{
2017-02-10 09:18:11 -05:00
data->resize(static_cast<uint32_t>(size));
stream.read(const_cast<char*>(data->data()), size);
stream.close();
return true;
2017-01-19 16:23:59 -05:00
}
}
2017-02-10 09:18:11 -05:00
return false;
2017-01-19 16:23:59 -05:00
}
size_t FileSize(std::string file)
{
if (FileExists(file))
{
std::ifstream stream(file, std::ios::binary);
if(stream.good())
{
stream.seekg(0, std::ios::end);
return static_cast<size_t>(stream.tellg());
}
}
return 0;
}
2017-02-10 16:02:13 -05:00
bool CreateDir(std::string dir)
2017-01-19 16:23:59 -05:00
{
return std::experimental::filesystem::create_directories(dir);
}
bool DirectoryExists(std::string directory)
{
return std::experimental::filesystem::is_directory(directory);
}
bool DirectoryIsEmpty(std::string directory)
{
return std::experimental::filesystem::is_empty(directory);
}
2017-01-19 16:23:59 -05:00
std::vector<std::string> ListFiles(std::string dir)
{
std::vector<std::string> files;
for (auto& file : std::experimental::filesystem::directory_iterator(dir))
{
files.push_back(file.path().generic_string());
}
return files;
}
}
}