From cf847cbfc99acd533b1189ed2544f19f9f19a147 Mon Sep 17 00:00:00 2001 From: Dennis Eichhorn Date: Fri, 16 Sep 2022 23:30:10 +0200 Subject: [PATCH] add file modification, file extension, read file --- Utils/FileUtils.h | 75 +++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 75 insertions(+) diff --git a/Utils/FileUtils.h b/Utils/FileUtils.h index ee8a4f4..a9e4823 100644 --- a/Utils/FileUtils.h +++ b/Utils/FileUtils.h @@ -11,6 +11,11 @@ #define UTILS_FILE_UTILS_H #ifdef _WIN32 + #include + #include + #include + #include + #ifdef _MSC_VER #include #else @@ -41,6 +46,76 @@ namespace Utils { return stat(filename, &buffer) == 0; #endif } + + static inline + time_t last_modification (char *filename) + { + #ifdef _WIN32 + FILETIME modtime; + HANDLE h; + + h = CreateFileW(filename, GENERIC_READ | FILE_WRITE_ATTRIBUTES, 0, NULL, OPEN_EXISTING, 0, NULL); + if (h == INVALID_HANDLE_VALUE) { + return (time_t) 0; + } + + if (GetFileTime(h, NULL, NULL, &modtime) == 0) { + return (time_t) 0; + } + + unsinged long long seconds = modtime.dwHighDateTime << 32; + seconds |= modtime.dwLowDateTime; + + return (seconds - 116444736000000000) / 10000000; + #elif defined __linux__ + struct stat buffer; + stat(filename, &buffer); + + (time_t) buffer.st_mtim.tv_sec; + #endif + } + + char* file_extension (char *filename) + { + char *dot = strrchr(filename, '.'); + + if (!dot || dot == filename) { + return ""; + } + + return dot + 1; + } + + typedef struct { + char *content; + int size; + } file_body; + + static inline + file_body read_file (char *filename) + { + file_body file = {0}; + + FILE *fp = fopen(filename, "rb"); + if (!fp) { + return NULL; + } + + fseek(fp, 0, SEEK_END); + file.size = ftell(fp); + fseek(fp, 0, SEEK_SET); + + file.content = malloc(file.size); + if (!file.content) { + fprintf(stderr, "CRITICAL: malloc failed"); + } + + fread(file.content, file.size, 1, fp); + + fclose(fp); + + return file; + } }; }