]> git.lizzy.rs Git - nothing.git/blob - src/system/file.c
Merge pull request #897 from RIscRIpt/last_mod_windows
[nothing.git] / src / system / file.c
1 #include <stdio.h>
2 #include <stdlib.h>
3 #ifdef __linux__
4 #include <sys/stat.h>
5 #include <sys/types.h>
6 #elif defined(_WIN32)
7 #include <Windows.h>
8 #define WINDOWS_TICK 10000000
9 #define SEC_TO_UNIX_EPOCH 11644473600LL
10 #endif // __linux__
11
12 #include "system/stacktrace.h"
13 #include "file.h"
14
15 time_t last_modified(const char *filepath)
16 {
17     trace_assert(filepath);
18
19 #ifdef __linux__
20     struct stat attr;
21     stat(filepath, &attr);
22     return attr.st_mtime;
23 #elif defined(_WIN32)
24     // CreateFile opens file (see flag OPEN_EXISTING)
25     HANDLE hFile = CreateFile(
26         filepath,
27         GENERIC_READ,
28         FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE,
29         NULL,
30         OPEN_EXISTING,
31         0,
32         NULL
33     );
34     if (!hFile) {
35         return 0;
36     }
37     FILETIME filetime = { 0 };
38     if (!GetFileTime(hFile, NULL, NULL, &filetime)) {
39         CloseHandle(hFile);
40         return 0;
41     }
42     CloseHandle(hFile);
43     unsigned long long mod_time = filetime.dwHighDateTime;
44     mod_time <<= 32;
45     mod_time |= filetime.dwLowDateTime;
46     // Taken from https://stackoverflow.com/a/6161842/1901561
47     return mod_time / WINDOWS_TICK - SEC_TO_UNIX_EPOCH;
48 #endif // __linux__
49 }