[IO] Safer file reading and writing
This commit is contained in:
parent
b3f83fe955
commit
cf05da99a1
@ -423,10 +423,11 @@ namespace Components
|
||||
return;
|
||||
}
|
||||
|
||||
std::string file;
|
||||
std::string fsGame = Dvar::Var("fs_game").get<std::string>();
|
||||
std::string path = Dvar::Var("fs_basepath").get<std::string>() + "\\" + fsGame + "\\" + url;
|
||||
|
||||
if (fsGame.empty() || !Utils::IO::FileExists(path))
|
||||
if (fsGame.empty() || !Utils::IO::ReadFile(path, &file))
|
||||
{
|
||||
mg_printf(nc,
|
||||
"HTTP/1.1 404 Not Found\r\n"
|
||||
@ -437,8 +438,6 @@ namespace Components
|
||||
}
|
||||
else
|
||||
{
|
||||
std::string file = Utils::IO::ReadFile(path);
|
||||
|
||||
mg_printf(nc,
|
||||
"HTTP/1.1 200 OK\r\n"
|
||||
"Content-Type: application/octet-stream\r\n"
|
||||
|
@ -9,7 +9,7 @@ namespace Utils
|
||||
return std::ifstream(file).good();
|
||||
}
|
||||
|
||||
void WriteFile(std::string file, std::string data, bool append)
|
||||
bool WriteFile(std::string file, std::string data, bool append)
|
||||
{
|
||||
auto pos = file.find_last_of("/\\");
|
||||
if (pos != std::string::npos)
|
||||
@ -23,17 +23,28 @@ namespace Utils
|
||||
{
|
||||
stream.write(data.data(), data.size());
|
||||
stream.close();
|
||||
return true;
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
std::string ReadFile(std::string file)
|
||||
{
|
||||
std::string buffer;
|
||||
std::string data;
|
||||
ReadFile(file, &data);
|
||||
return data;
|
||||
}
|
||||
|
||||
bool ReadFile(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 buffer;
|
||||
if (!stream.is_open()) return false;
|
||||
|
||||
stream.seekg(0, std::ios::end);
|
||||
std::streamsize size = stream.tellg();
|
||||
@ -41,16 +52,16 @@ namespace Utils
|
||||
|
||||
if (size > -1)
|
||||
{
|
||||
buffer.clear();
|
||||
buffer.resize(static_cast<uint32_t>(size));
|
||||
|
||||
stream.read(const_cast<char*>(buffer.data()), size);
|
||||
data->resize(static_cast<uint32_t>(size));
|
||||
stream.read(const_cast<char*>(data->data()), size);
|
||||
stream.close();
|
||||
return true;
|
||||
}
|
||||
|
||||
stream.close();
|
||||
}
|
||||
|
||||
return buffer;
|
||||
return false;
|
||||
}
|
||||
|
||||
bool CreateDirectory(std::string dir)
|
||||
|
@ -5,7 +5,8 @@ namespace Utils
|
||||
namespace IO
|
||||
{
|
||||
bool FileExists(std::string file);
|
||||
void WriteFile(std::string file, std::string data, bool append = false);
|
||||
bool WriteFile(std::string file, std::string data, bool append = false);
|
||||
bool ReadFile(std::string file, std::string* data);
|
||||
std::string ReadFile(std::string file);
|
||||
bool CreateDirectory(std::string dir);
|
||||
std::vector<std::string> ListFiles(std::string dir);
|
||||
|
Loading…
Reference in New Issue
Block a user