Files
jadeite/game_payload/src/utils.c

67 lines
1.8 KiB
C
Raw Normal View History

2023-06-06 00:23:08 +03:00
#include <windows.h>
#include <crc32.h>
2023-06-08 21:44:42 +03:00
#include <msg.h>
2023-06-06 00:23:08 +03:00
#include <utils.h>
2023-08-04 22:55:10 +03:00
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);
2023-06-06 00:23:08 +03:00
if (!file) {
msg_err_w(L"Could not open file: %ls", filePath);
2023-06-06 00:23:08 +03:00
}
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);
2023-06-06 00:23:08 +03:00
}
2023-08-04 22:17:31 +03:00
uint32_t crc = crc32c(0, map, fileSize.QuadPart);
2023-06-06 00:23:08 +03:00
UnmapViewOfFile(map);
CloseHandle(hMap);
CloseHandle(file);
return crc;
}
2023-06-08 22:33:37 +03:00
2023-08-04 22:55:10 +03:00
// https://stackoverflow.com/a/16719260
void utils_create_parent_dirs(const wchar_t *path) {
2023-08-04 22:55:10 +03:00
wchar_t dir[MAX_PATH];
ZeroMemory(dir, sizeof(dir));
2023-08-04 22:55:10 +03:00
const wchar_t *end = path - 1;
2023-08-04 22:55:10 +03:00
while((end = wcschr(++end, L'\\')) != NULL) {
2023-08-04 22:55:10 +03:00
wcsncpy(dir, path, end - path + 1);
if (!utils_path_exists(dir) && !CreateDirectoryW(dir, NULL)) {
msg_err_w(L"Failed to create directory: %ls", dir);
}
}
}
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);
}
2023-06-08 22:33:37 +03:00
char utils_env_enabled(const char *env) {
char *envText = getenv(env);
2023-07-03 17:04:32 +03:00
return envText && *envText;
2023-06-08 22:33:37 +03:00
}