summaryrefslogtreecommitdiff
path: root/src/statvfs_helper.c
blob: b22d2d13930a07503c849b74cfbc35d714b70baf (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
#include <stdint.h>

#ifdef _WIN32
#include <windows.h>
#include <string.h>
#include <stdio.h>

uint64_t statvfs_get_free_space_impl(const char* path) {
    ULARGE_INTEGER freeBytesAvailable;
    ULARGE_INTEGER totalNumberOfBytes;
    ULARGE_INTEGER totalNumberOfFreeBytes;

    // GetDiskFreeSpaceExA expects a directory path, so we need to extract the root directory
    // For simplicity, we'll use the current directory if path is a file
    char root_path[MAX_PATH];

    // If path is already a root (like "C:" or "C:\"), use it directly
    if (strlen(path) >= 2 && path[1] == ':') {
        snprintf(root_path, sizeof(root_path), "%c:\\", path[0]);
    } else {
        // For relative paths or files, get the current directory
        if (GetCurrentDirectoryA(sizeof(root_path), root_path) == 0) {
            return 0;
        }
        // Ensure it ends with backslash for GetDiskFreeSpaceExA
        size_t len = strlen(root_path);
        if (len > 0 && root_path[len - 1] != '\\') {
            if (len < sizeof(root_path) - 1) {
                root_path[len] = '\\';
                root_path[len + 1] = '\0';
            }
        }
    }

    if (GetDiskFreeSpaceExA(root_path, &freeBytesAvailable, &totalNumberOfBytes, &totalNumberOfFreeBytes)) {
        return (uint64_t)freeBytesAvailable.QuadPart;
    }

    return 0;
}
#else
#include <sys/statvfs.h>

uint64_t statvfs_get_free_space_impl(const char* path) {
    struct statvfs stat;
    if (statvfs(path, &stat) != 0) {
        return 0;
    }
    return (uint64_t)stat.f_frsize * (uint64_t)stat.f_bavail;
}
#endif