#include "../include/FileUtil.hpp" #include using namespace std; namespace sibs { FileType getFileType(const char *path) { tinydir_file file; if(tinydir_file_open(&file, path) == 0) { return file.is_dir ? FileType::DIRECTORY : FileType::REGULAR; } else { return FileType::FILE_NOT_FOUND; } } // TODO: Handle failure (directory doesn't exist, no permission etc) void walkDirFiles(const char *directory, FileWalkCallbackFunc callbackFunc) { tinydir_dir dir; tinydir_open(&dir, directory); while (dir.has_next) { tinydir_file file; tinydir_readfile(&dir, &file); if(file.is_reg) callbackFunc(&file); else if(_tinydir_strcmp(file.name, ".") != 0 && _tinydir_strcmp(file.name, "..") != 0) walkDirFiles(file.path, callbackFunc); tinydir_next(&dir); } tinydir_close(&dir); } Result getFileContent(const char *filepath) { FILE *file = fopen(filepath, "rb"); if(!file || errno != 0) { perror(filepath); return Result::Err("Failed to open file"); } fseek(file, 0, SEEK_END); size_t fileSize = ftell(file); fseek(file, 0, SEEK_SET); // TODO: Change this to string so it can be deallocated and use std::move to prevent copies char *result = (char*)malloc(fileSize + 1); if(!result) { std::string errMsg = "Failed to load file content from file: "; errMsg += filepath; throw std::runtime_error(errMsg); } result[fileSize] = '\0'; fread(result, 1, fileSize, file); fclose(file); return Result::Ok(StringView(result, fileSize)); } bool fileOverwrite(const char *filepath, StringView data) { FILE *file = fopen(filepath, "wb"); if(!file || errno != 0) { perror(filepath); return false; } fwrite(data.data, 1, data.size, file); fclose(file); } }