Advertisement
alexarcan

lab5_os_mi

Oct 28th, 2015
354
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.88 KB | None | 0 0
  1. /*
  2. http://stackoverflow.com/questions/3138600/correct-use-of-stat-on-c
  3. http://www.electro.fisica.unlp.edu.ar/temas/p5/files.html //explicatii directoare
  4. https://www.cs.cf.ac.uk/Dave/C/node20.html#SECTION002000000000000000000 //~directoare
  5. */
  6.  
  7. #include <stdio.h>
  8. #include <dirent.h>
  9. #include <string.h>
  10. #include <sys/types.h>
  11. #include <sys/stat.h>
  12. #include <unistd.h>
  13.  
  14.  
  15. long int computeDirectorySize(const char* name){
  16.  
  17. DIR* dir = opendir(name);
  18.  
  19. long int totalSize = 0;
  20.  
  21. struct dirent* currentFile;
  22.  
  23. while((currentFile = readdir(dir)) != NULL){
  24.  
  25. if(strcmp(currentFile->d_name, "..") == 0 || strcmp(currentFile->d_name, ".") == 0){
  26. continue;
  27. }
  28.  
  29. struct stat file_status;
  30.  
  31. if (stat(currentFile->d_name, &file_status) == 0) {
  32.  
  33. char dirName[30] = "";
  34. //strcat(dirName, name);
  35. strcat(dirName, "/");
  36. strcat(dirName, currentFile->d_name);
  37. printf("%s\n", dirName);
  38.  
  39. if (S_ISDIR(file_status.st_mode)){
  40. printf("%s is a directory\n", currentFile->d_name);
  41. totalSize += computeDirectorySize(dirName);
  42. }
  43.  
  44.  
  45.  
  46. else if(S_ISREG(file_status.st_mode)){
  47. printf("%s is a normal file\n", currentFile->d_name);
  48. //printf("%d \n", file_status.st_size);
  49. totalSize += file_status.st_size;
  50. }
  51.  
  52. else{
  53. continue;
  54. }
  55. }
  56. else { /* stat() call failed and returned '-1'. */
  57. perror("stat call failed");
  58. }
  59. }
  60.  
  61. closedir(dir);
  62.  
  63. return totalSize;
  64. }
  65.  
  66.  
  67. int main(int argc, char *argv[])
  68. {
  69. if(argc == 1)
  70. {
  71. fprintf(stderr, "Please give one or more directory names! %d\r\n", argc);
  72. return 1;
  73. }
  74.  
  75. int i;
  76. for(i=1; i<argc; i++){
  77. long int totalSize = computeDirectorySize(argv[i]);
  78. printf("Dimensiunea totala a directorului %s este : %d bytes.\n\n", argv[i], totalSize);
  79. }
  80.  
  81. return 0;
  82. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement