LibFileSystem: Add a method to query disk space stats

This returns the amount of free and total disk space for the partition
of a provided path.
This commit is contained in:
Timothy Flynn
2026-02-04 17:49:11 -05:00
committed by Tim Flynn
parent 49d24f1867
commit 551b82ae0b
Notes: github-actions[bot] 2026-02-13 15:22:48 +00:00
2 changed files with 42 additions and 5 deletions

View File

@@ -11,12 +11,16 @@
#include <LibCore/System.h>
#include <LibFileSystem/FileSystem.h>
#if !defined(AK_OS_IOS) && defined(AK_OS_BSD_GENERIC)
# include <sys/disk.h>
#elif defined(AK_OS_LINUX)
# include <linux/fs.h>
#elif defined(AK_OS_WINDOWS)
#if defined(AK_OS_WINDOWS)
# include <windows.h>
#else
# include <sys/statvfs.h>
# if !defined(AK_OS_IOS) && defined(AK_OS_BSD_GENERIC)
# include <sys/disk.h>
# elif defined(AK_OS_LINUX)
# include <linux/fs.h>
# endif
#endif
// On Linux distros that use glibc `basename` is defined as a macro that expands to `__xpg_basename`, so we undefine it
@@ -363,4 +367,30 @@ ErrorOr<off_t> size_from_fstat(int fd)
return st.st_size;
}
ErrorOr<DiskSpace> compute_disk_space(LexicalPath const& path)
{
#if defined(AK_OS_WINDOWS)
ULARGE_INTEGER free_bytes;
ULARGE_INTEGER total_bytes;
if (!GetDiskFreeSpaceExA(path.string().characters(), &free_bytes, &total_bytes, nullptr))
return Error::from_windows_error();
return DiskSpace {
.free_bytes = free_bytes.QuadPart,
.total_bytes = total_bytes.QuadPart,
};
#else
struct statvfs stats {};
if (::statvfs(path.string().characters(), &stats) != 0)
return Error::from_syscall("statvfs"sv, errno);
return DiskSpace {
.free_bytes = stats.f_bavail * stats.f_frsize,
.total_bytes = stats.f_blocks * stats.f_frsize,
};
#endif
}
}