df.c 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <string.h>
  4. #include <errno.h>
  5. #include <sys/statfs.h>
  6. static int ok = EXIT_SUCCESS;
  7. static void printsize(long long n)
  8. {
  9. char unit = 'K';
  10. long long t;
  11. n *= 10;
  12. if (n > 1024*1024*10) {
  13. n /= 1024;
  14. unit = 'M';
  15. }
  16. if (n > 1024*1024*10) {
  17. n /= 1024;
  18. unit = 'G';
  19. }
  20. t = (n + 512) / 1024;
  21. printf("%4lld.%1lld%c", t/10, t%10, unit);
  22. }
  23. static void df(char *s, int always) {
  24. struct statfs st;
  25. if (statfs(s, &st) < 0) {
  26. fprintf(stderr, "%s: %s\n", s, strerror(errno));
  27. ok = EXIT_FAILURE;
  28. } else {
  29. if (st.f_blocks == 0 && !always)
  30. return;
  31. printf("%-20s ", s);
  32. printsize((long long)st.f_blocks * (long long)st.f_bsize);
  33. printf(" ");
  34. printsize((long long)(st.f_blocks - (long long)st.f_bfree) * st.f_bsize);
  35. printf(" ");
  36. printsize((long long)st.f_bfree * (long long)st.f_bsize);
  37. printf(" %d\n", (int) st.f_bsize);
  38. }
  39. }
  40. int main(int argc, char *argv[]) {
  41. printf("Filesystem Size Used Free Blksize\n");
  42. if (argc == 1) {
  43. char s[2000];
  44. FILE *f = fopen("/proc/mounts", "r");
  45. while (fgets(s, 2000, f)) {
  46. char *c, *e = s;
  47. for (c = s; *c; c++) {
  48. if (*c == ' ') {
  49. e = c + 1;
  50. break;
  51. }
  52. }
  53. for (c = e; *c; c++) {
  54. if (*c == ' ') {
  55. *c = '\0';
  56. break;
  57. }
  58. }
  59. df(e, 0);
  60. }
  61. fclose(f);
  62. } else {
  63. int i;
  64. for (i = 1; i < argc; i++) {
  65. df(argv[i], 1);
  66. }
  67. }
  68. exit(ok);
  69. }