70 lines
1.8 KiB
C
70 lines
1.8 KiB
C
#include <windows.h>
|
|
|
|
#include <crc32.h>
|
|
#include <msg.h>
|
|
|
|
#include <utils.h>
|
|
|
|
int utils_path_exists(const wchar_t *filePath) {
|
|
return GetFileAttributesW(filePath) != INVALID_FILE_ATTRIBUTES;
|
|
}
|
|
|
|
uint32_t utils_file_crc32c(const wchar_t *filePath) {
|
|
HANDLE file = CreateFileW(filePath, FILE_READ_ACCESS, FILE_SHARE_READ, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
|
|
if (!file) {
|
|
msg_err_w(L"Could not open file: %ls", filePath);
|
|
}
|
|
|
|
LARGE_INTEGER fileSize;
|
|
GetFileSizeEx(file, &fileSize);
|
|
|
|
HANDLE hMap = CreateFileMappingA(file, NULL, PAGE_READONLY, 0, 0, NULL);
|
|
char *map = MapViewOfFile(hMap, FILE_MAP_READ, 0, 0, 0);
|
|
if (!map) {
|
|
msg_err_w(L"Could not create file mapping for %ls", filePath);
|
|
}
|
|
|
|
uint32_t crc = crc32c(0, map, fileSize.QuadPart);
|
|
|
|
UnmapViewOfFile(map);
|
|
CloseHandle(hMap);
|
|
CloseHandle(file);
|
|
|
|
return crc;
|
|
}
|
|
|
|
// https://stackoverflow.com/a/16719260
|
|
void utils_create_dir_recursively(const wchar_t *path) {
|
|
wchar_t dir[MAX_PATH];
|
|
ZeroMemory(dir, MAX_PATH * sizeof(wchar_t));
|
|
|
|
wchar_t *end = wcschr(path, L'\\');
|
|
|
|
while(end != NULL)
|
|
{
|
|
wcsncpy(dir, path, end - path + 1);
|
|
|
|
if (!utils_path_exists(dir) && !CreateDirectoryW(dir, NULL)) {
|
|
msg_err_w(L"Failed to create directory: %ls", dir);
|
|
}
|
|
|
|
end = wcschr(++end, L'\\');
|
|
}
|
|
}
|
|
|
|
void utils_save_to_file(const wchar_t *filePath, const void *buf, size_t length) {
|
|
HANDLE file = CreateFileW(filePath, FILE_WRITE_ACCESS, FILE_SHARE_READ, NULL, CREATE_NEW, FILE_ATTRIBUTE_NORMAL, NULL);
|
|
if (!file) {
|
|
msg_err_w(L"Could not open file: %ls", filePath);
|
|
}
|
|
|
|
WriteFile(file, buf, length, NULL, FALSE);
|
|
|
|
CloseHandle(file);
|
|
}
|
|
|
|
char utils_env_enabled(const char *env) {
|
|
char *envText = getenv(env);
|
|
return envText && *envText;
|
|
}
|