Advertisement
fr1sk

Untitled

Mar 31st, 2017
105
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.06 KB | None | 0 0
  1. #define _XOPEN_SOURCE 700
  2. #include <stdio.h>
  3. #include <stdlib.h>
  4. #include <stdbool.h>
  5. #include <stdint.h>
  6. #include <stdint.h>
  7. #include <unistd.h>
  8. #include <sys/types.h>
  9. #include <sys/stat.h>
  10. #include <unistd.h>
  11. #include <sys/types.h>
  12. #include <sys/stat.h>
  13. #include <fcntl.h>
  14. #include <sys/types.h>
  15. #include <dirent.h>
  16. #include <sys/types.h>
  17. #include <sys/stat.h>
  18. #include <unistd.h>
  19. #include <string.h>
  20.  
  21. #define osAssert(state, msg) osErrorFatal(state, msg, __LINE__, __FILE__)
  22.  
  23. void osErrorFatal(bool state, const char *msg, int lineNum, const char *fname){
  24. if(!state){
  25. perror(msg);
  26. fprintf(stderr, "%s:%d\n",fname, lineNum);
  27. exit(EXIT_FAILURE);
  28. }
  29. }
  30.  
  31. int osCalculateFolderSize(char *path, unsigned *size){
  32. DIR *dirFD= opendir(path);
  33. if(dirFD == NULL){
  34. return false;
  35. }
  36. struct dirent *folder;
  37. struct stat buf;
  38. while((folder=readdir(dirFD))!=NULL){
  39. //printf("%s\n", folder->d_name);
  40. // const char *pathname, struct stat *buf
  41. // *;
  42.  
  43. if(strcmp(".",folder->d_name) || strcmp("..",folder->d_name)){
  44. continue;
  45. } else {
  46. char* newPath = strndup(path, strlen(path)+1+strlen(folder->d_name));
  47. strcat(newPath, "/");
  48. strcat(newPath, folder->d_name);
  49. printf("p: %s\n", newPath);
  50. osAssert(-1!=lstat(newPath, &buf),"lstat failed inwhile");
  51.  
  52. if(S_ISDIR(buf.st_mode)){
  53. osAssert(-1!=osCalculateFolderSize(newPath, size),"failed to calculate dir size");
  54. } else {
  55. *size += buf.st_size;
  56. }
  57.  
  58.  
  59. }
  60. }
  61. return 0;
  62. }
  63.  
  64. int main(int argc, char **argv){
  65. osAssert(2==argc,"wrong num of args");
  66. struct stat buf;
  67. osAssert(-1!=lstat(argv[1],&buf),"stat failed");
  68. osAssert(S_ISDIR(buf.st_mode), "this is not dir");
  69. unsigned size = 0;
  70. osAssert(-1!=osCalculateFolderSize(argv[1], &size),"failed to calculate dir size");
  71. printf("\n");
  72. printf("size: %u\n",size);
  73. return 0;
  74. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement