FileSystem: Add ReadFileWithProgress()

This commit is contained in:
Stenzek 2024-06-10 02:27:30 +10:00 committed by Connor McLaughlin
parent 8a3513f2ba
commit e1596c7911
2 changed files with 29 additions and 0 deletions

View File

@ -8,6 +8,7 @@
#include "Console.h"
#include "StringUtil.h"
#include "Path.h"
#include "ProgressCallback.h"
#include <algorithm>
#include <cerrno>
@ -1183,6 +1184,31 @@ bool FileSystem::WriteStringToFile(const char* filename, const std::string_view
return true;
}
size_t FileSystem::ReadFileWithProgress(std::FILE* fp, void* dst, size_t length,
ProgressCallback* progress, Error* error, size_t chunk_size)
{
progress->SetProgressRange(100);
size_t done = 0;
while (done < length)
{
if (progress->IsCancelled())
break;
const size_t read_size = std::min(length - done, chunk_size);
if (std::fread(static_cast<u8*>(dst)+ done, read_size, 1, fp) != 1)
{
Error::SetErrno(error, "fread() failed: ", errno);
break;
}
progress->SetProgressValue((done * 100) / length);
done += read_size;
}
return done;
}
bool FileSystem::EnsureDirectoryExists(const char* path, bool recursive, Error* error)
{
if (FileSystem::DirectoryExists(path))

View File

@ -14,6 +14,7 @@
#include <sys/stat.h>
class Error;
class ProgressCallback;
#ifdef _WIN32
#define FS_OSPATH_SEPARATOR_CHARACTER '\\'
@ -131,6 +132,8 @@ namespace FileSystem
std::optional<std::string> ReadFileToString(std::FILE* fp);
bool WriteBinaryFile(const char* filename, const void* data, size_t data_length);
bool WriteStringToFile(const char* filename, const std::string_view sv);
size_t ReadFileWithProgress(std::FILE* fp, void* dst, size_t length, ProgressCallback* progress,
Error* error = nullptr, size_t chunk_size = 16 * 1024 * 1024);
/// creates a directory in the local filesystem
/// if the directory already exists, the return value will be true.