micro-utils/src/coreutils/df/df.c

93 lines
2.1 KiB
C

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdint.h>
#include <errno.h>
#include <unistd.h>
#include <mntent.h>
#include <sys/statvfs.h>
#include "human.h"
#include "config.h"
unsigned int a_flag;
unsigned int h_flag;
off_t block = 1024;
void print_human(const char *src, const off_t total, const off_t used, const off_t avail, const off_t capacity, const char *dst) {
char total_s[MU_HUMAN_BUF_SIZE + 1];
char used_s[MU_HUMAN_BUF_SIZE + 1];
char avail_s[MU_HUMAN_BUF_SIZE + 1];
snprintf(total_s, sizeof(total_s), "%s", mu_humansize(total * block, block));
snprintf(used_s, sizeof(used_s), "%s", mu_humansize(used * block, block));
snprintf(avail_s, sizeof(avail_s), "%s", mu_humansize(avail * block, block));
printf("%-20s %5s %5s %5s %7ju%% %s\n", src, total_s, used_s, avail_s, capacity, dst);
}
int main(int argc, char **argv) {
int opt;
while ((opt = getopt(argc, argv, "hHka")) != -1) {
switch (opt) {
case 'h':
h_flag = 1;
break;
case 'H':
h_flag = 1;
block = 1000;
break;
case 'a':
a_flag = 1;
break;
default:
printf("df\n\t[-h Human readable (1024)] [-a Show all]\n\t[-H Human readable (1000)]\n");
return 0;
}
}
FILE *fp = setmntent("/proc/mounts", "r");
if (fp == NULL) {
fprintf(stderr, "df: %s\n", strerror(errno));
return 1;
}
printf("[Filesystem] [Size] [Used] [Avail] [Capacity] [Mounted on]\n");
int ret = 0;
struct mntent *me;
struct statvfs disk;
while ((me = getmntent(fp)) != NULL) {
if (!strcmp(me->mnt_fsname, "none"))
continue;
if (!a_flag)
if (!strncmp(me->mnt_fsname, "fs", 2))
continue;
if (statvfs(me->mnt_dir, &disk) < 0) {
ret = 1;
continue;
}
off_t bs = disk.f_frsize / block;
off_t total = disk.f_blocks * bs;
off_t avail = disk.f_bfree * bs;
off_t used = total - avail;
off_t capacity = (used * 100) / (avail + used) + 1;
if (h_flag)
print_human(me->mnt_fsname, total, used, avail, capacity, me->mnt_dir);
else
printf("%-20s %7ju %7ju %7ju %7ju%% %s\n", me->mnt_fsname, total, used, avail, capacity, me->mnt_dir);
}
endmntent(fp);
return ret;
}