2021-04-07 00:23:23 +02:00
|
|
|
#include "fs/FSUtils.h"
|
|
|
|
#include "utils/logger.h"
|
2022-02-14 20:23:27 +01:00
|
|
|
#include "utils/utils.h"
|
|
|
|
#include <cstdio>
|
|
|
|
#include <cstring>
|
2022-02-04 16:25:44 +01:00
|
|
|
#include <fcntl.h>
|
2023-11-04 15:32:45 +01:00
|
|
|
#include <filesystem>
|
2022-02-04 16:25:44 +01:00
|
|
|
#include <unistd.h>
|
2023-11-04 15:32:45 +01:00
|
|
|
#include <vector>
|
2021-04-07 00:23:23 +02:00
|
|
|
|
2023-11-04 15:32:45 +01:00
|
|
|
int32_t FSUtils::LoadFileToMem(std::string_view filepath, std::vector<uint8_t> &buffer) {
|
|
|
|
//! always initialize input
|
|
|
|
buffer.clear();
|
2021-04-07 00:23:23 +02:00
|
|
|
|
2023-11-04 15:32:45 +01:00
|
|
|
int32_t iFd = open(filepath.data(), O_RDONLY);
|
2022-02-14 20:23:27 +01:00
|
|
|
if (iFd < 0) {
|
2021-04-07 00:23:23 +02:00
|
|
|
return -1;
|
2022-02-14 20:23:27 +01:00
|
|
|
}
|
2021-04-07 00:23:23 +02:00
|
|
|
|
2023-11-04 15:32:45 +01:00
|
|
|
struct stat file_stat {};
|
2022-08-08 11:55:13 +02:00
|
|
|
int rc = fstat(iFd, &file_stat);
|
|
|
|
if (rc < 0) {
|
|
|
|
close(iFd);
|
|
|
|
return -4;
|
|
|
|
}
|
|
|
|
uint32_t filesize = file_stat.st_size;
|
2021-04-07 00:23:23 +02:00
|
|
|
|
2023-11-04 15:32:45 +01:00
|
|
|
buffer.resize(filesize);
|
2021-04-07 00:23:23 +02:00
|
|
|
|
2022-08-08 11:55:13 +02:00
|
|
|
uint32_t blocksize = 0x80000;
|
2022-02-04 16:25:44 +01:00
|
|
|
uint32_t done = 0;
|
2022-08-08 11:55:13 +02:00
|
|
|
int32_t readBytes;
|
2021-04-07 00:23:23 +02:00
|
|
|
|
|
|
|
while (done < filesize) {
|
|
|
|
if (done + blocksize > filesize) {
|
|
|
|
blocksize = filesize - done;
|
|
|
|
}
|
2023-11-04 15:32:45 +01:00
|
|
|
readBytes = read(iFd, buffer.data() + done, blocksize);
|
2022-08-08 11:55:13 +02:00
|
|
|
if (readBytes <= 0) {
|
2021-04-07 00:23:23 +02:00
|
|
|
break;
|
2022-08-08 11:55:13 +02:00
|
|
|
}
|
2021-04-07 00:23:23 +02:00
|
|
|
done += readBytes;
|
|
|
|
}
|
|
|
|
|
2022-02-14 20:23:27 +01:00
|
|
|
::close(iFd);
|
2021-04-07 00:23:23 +02:00
|
|
|
|
|
|
|
if (done != filesize) {
|
2023-11-04 15:32:45 +01:00
|
|
|
buffer.clear();
|
2021-04-07 00:23:23 +02:00
|
|
|
return -3;
|
|
|
|
}
|
|
|
|
|
|
|
|
return 0;
|
|
|
|
}
|
|
|
|
|
2023-11-04 15:32:45 +01:00
|
|
|
bool FSUtils::CreateSubfolder(std::string_view fullpath) {
|
|
|
|
std::error_code err;
|
|
|
|
if (!std::filesystem::create_directories(fullpath, err)) {
|
|
|
|
return std::filesystem::exists(fullpath, err);
|
2021-04-07 00:23:23 +02:00
|
|
|
}
|
2023-11-04 15:32:45 +01:00
|
|
|
return true;
|
2021-04-07 00:23:23 +02:00
|
|
|
}
|