freespace.c 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. /* Copyright (c) 2003-2004, Roger Dingledine
  2. * Copyright (c) 2004-2006, Roger Dingledine, Nick Mathewson.
  3. * Copyright (c) 2007-2018, The Tor Project, Inc. */
  4. /* See LICENSE for licensing information */
  5. /**
  6. * \file freespace.c
  7. *
  8. * \brief Find the available disk space on the current volume.
  9. **/
  10. #include "lib/fs/files.h"
  11. #include "lib/cc/torint.h"
  12. #ifdef HAVE_SYS_STATVFS_H
  13. #include <sys/statvfs.h>
  14. #endif
  15. #ifdef _WIN32
  16. #include <windows.h>
  17. #endif
  18. #include <string.h>
  19. /** Return the amount of free disk space we have permission to use, in
  20. * bytes. Return -1 if the amount of free space can't be determined. */
  21. int64_t
  22. tor_get_avail_disk_space(const char *path)
  23. {
  24. #ifdef HAVE_STATVFS
  25. struct statvfs st;
  26. int r;
  27. memset(&st, 0, sizeof(st));
  28. r = statvfs(path, &st);
  29. if (r < 0)
  30. return -1;
  31. int64_t result = st.f_bavail;
  32. if (st.f_frsize) {
  33. result *= st.f_frsize;
  34. } else if (st.f_bsize) {
  35. result *= st.f_bsize;
  36. } else {
  37. return -1;
  38. }
  39. return result;
  40. #elif defined(_WIN32)
  41. ULARGE_INTEGER freeBytesAvail;
  42. BOOL ok;
  43. ok = GetDiskFreeSpaceEx(path, &freeBytesAvail, NULL, NULL);
  44. if (!ok) {
  45. return -1;
  46. }
  47. return (int64_t)freeBytesAvail.QuadPart;
  48. #else
  49. (void)path;
  50. errno = ENOSYS;
  51. return -1;
  52. #endif /* defined(HAVE_STATVFS) || ... */
  53. }