dirsize.c 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. /*
  2. *
  3. * Copyright (C) 2008, The Android Open Source Project
  4. *
  5. * Licensed under the Apache License, Version 2.0 (the "License");
  6. * you may not use this file except in compliance with the License.
  7. * You may obtain a copy of the License at
  8. *
  9. * http://www.apache.org/licenses/LICENSE-2.0
  10. *
  11. * Unless required by applicable law or agreed to in writing, software
  12. * distributed under the License is distributed on an "AS IS" BASIS,
  13. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14. * See the License for the specific language governing permissions and
  15. * limitations under the License.
  16. */
  17. #include <dirent.h>
  18. #include <fcntl.h>
  19. #include <sys/stat.h>
  20. #include <unistd.h>
  21. #include <diskusage/dirsize.h>
  22. int64_t stat_size(struct stat *s)
  23. {
  24. int64_t blksize = s->st_blksize;
  25. // count actual blocks used instead of nominal file size
  26. int64_t size = s->st_blocks * 512;
  27. if (blksize) {
  28. /* round up to filesystem block size */
  29. size = (size + blksize - 1) & (~(blksize - 1));
  30. }
  31. return size;
  32. }
  33. int64_t calculate_dir_size(int dfd)
  34. {
  35. int64_t size = 0;
  36. struct stat s;
  37. DIR *d;
  38. struct dirent *de;
  39. d = fdopendir(dfd);
  40. if (d == NULL) {
  41. close(dfd);
  42. return 0;
  43. }
  44. while ((de = readdir(d))) {
  45. const char *name = de->d_name;
  46. if (fstatat(dfd, name, &s, AT_SYMLINK_NOFOLLOW) == 0) {
  47. size += stat_size(&s);
  48. }
  49. if (de->d_type == DT_DIR) {
  50. int subfd;
  51. /* always skip "." and ".." */
  52. if (name[0] == '.') {
  53. if (name[1] == 0)
  54. continue;
  55. if ((name[1] == '.') && (name[2] == 0))
  56. continue;
  57. }
  58. subfd = openat(dfd, name, O_RDONLY | O_DIRECTORY);
  59. if (subfd >= 0) {
  60. size += calculate_dir_size(subfd);
  61. }
  62. }
  63. }
  64. closedir(d);
  65. return size;
  66. }