Is there a function that returns how much space is free on a drive partition given a directory path?
views:
73answers:
2
+1
A:
Use df -h /path/to/directory
(mnemonically, "disk free"). The -h
flag causes it to use human-readable, base-2 sizes (based on 1024 bytes to the kilobyte) rather than a raw count of 512-byte blocks. You can get base-10 sizes (based on 1000 bytes to the kilobyte - you know, the sizes the hard-disk manufacturers advertise) by using -H
.
Example:
$ df -h .
Filesystem Size Used Avail Capacity Mounted on
/dev/disk0s2 233Gi 82Gi 150Gi 36% /
To attribute usage, use du -h /path
(disk usage).
Jeremy W. Sherman
2010-10-21 21:35:12
He's looking for a function, not a command
Michael Mrozek
2010-10-21 21:37:10
Good point - I did not read closely enough. But, knowing my answer, he could answer his own question by doing `nm /bin/df` or tracking down the source to `df` on his system. Once you have a tool that does something, you just have to poke inside to find out how it does it.
Jeremy W. Sherman
2010-10-21 21:41:57
+5
A:
check man statvfs(2)
I believe you can calculate 'free space' as f_bsize * f_bfree
.
NAME
statvfs, fstatvfs - get file system statistics
SYNOPSIS
#include <sys/statvfs.h>
int statvfs(const char *path, struct statvfs *buf);
int fstatvfs(int fd, struct statvfs *buf);
DESCRIPTION
The function statvfs() returns information about a mounted file system.
path is the pathname of any file within the mounted file system. buf
is a pointer to a statvfs structure defined approximately as follows:
struct statvfs {
unsigned long f_bsize; /* file system block size */
unsigned long f_frsize; /* fragment size */
fsblkcnt_t f_blocks; /* size of fs in f_frsize units */
fsblkcnt_t f_bfree; /* # free blocks */
fsblkcnt_t f_bavail; /* # free blocks for unprivileged users */
fsfilcnt_t f_files; /* # inodes */
fsfilcnt_t f_ffree; /* # free inodes */
fsfilcnt_t f_favail; /* # free inodes for unprivileged users */
unsigned long f_fsid; /* file system ID */
unsigned long f_flag; /* mount flags */
unsigned long f_namemax; /* maximum filename length */
};
John Ledbetter
2010-10-21 21:36:45