static int ok = EXIT_SUCCESS;
//根据挂载的文件的大小来计算
static void printsize(long double n)
{
char unit = 'K';
n /= 1024;
if (n > 1024) {
n /= 1024;
unit = 'M';
}
if (n > 1024) {
n /= 1024;
unit = 'G';
}
printf("%-4.1Lf%c", n, unit);
}
static void df(char *s, int always) {
//
struct statfs st;
//statfs函数可用来查询文件系统相关的信息。
if (statfs(s, &st) < 0) {
fprintf(stderr, "%s: %s\n", s, strerror(errno));
ok = EXIT_FAILURE;
} else {
if (st.f_blocks == 0 && !always)
return;
printf("%-20s ", s);
printsize((long double)st.f_blocks * (long double)st.f_bsize);
printf(" ");
printsize((long double)(st.f_blocks - (long double)st.f_bfree) * st.f_bsize);
printf(" ");
printsize((long double)st.f_bfree * (long double)st.f_bsize);
printf(" %d\n", (int) st.f_bsize);
}
}
int df_main(int argc, char *argv[]) {
printf("Filesystem Size Used Free Blksize\n");
if (argc == 1) {
char s[2000];
//挂载的文件都在/proc/mounts下显示
FILE *f = fopen("/proc/mounts", "r");
while (fgets(s, 2000, f)) {
char *c, *e = s;
for (c = s; *c; c++) {
if (*c == ' ') {
e = c + 1;
break;
}
}
for (c = e; *c; c++) {
if (*c == ' ') {
*c = '\0';
break;
}
}
df(e, 0);
}
fclose(f);
} else {
int i;
for (i = 1; i < argc; i++) {
df(argv[i], 1);
}
}