Advertisement
pasholnahuy

Untitled

May 25th, 2024
566
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.27 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <string.h>
  4. #include <unistd.h>
  5. #include <sys/stat.h>
  6. #include <dirent.h>
  7.  
  8. #define MAX_DEPTH 4
  9.  
  10. void print_regular_files(const char* dir_path, int depth, off_t max_size) {
  11.     DIR* dir = opendir(dir_path);
  12.     if (dir == NULL) {
  13.         return;
  14.     }
  15.  
  16.     struct dirent* entry;
  17.     while ((entry = readdir(dir)) != NULL) {
  18.         if (strcmp(entry->d_name, ".") == 0 || strcmp(entry->d_name, "..") == 0) {
  19.             continue;
  20.         }
  21.  
  22.         char path[PATH_MAX];
  23.         snprintf(path, sizeof(path), "%s/%s", dir_path, entry->d_name);
  24.  
  25.         struct stat st;
  26.         if (lstat(path, &st) == -1) {
  27.             continue;
  28.         }
  29.  
  30.         if (S_ISREG(st.st_mode) && access(path, R_OK) != -1 && st.st_size <= max_size) {
  31.             printf("%s\n", entry->d_name);
  32.         } else if (S_ISDIR(st.st_mode) && depth < MAX_DEPTH) {
  33.             print_regular_files(path, depth + 1, max_size);
  34.         }
  35.     }
  36.  
  37.     closedir(dir);
  38. }
  39.  
  40. int main(int argc, char* argv[]) {
  41.     if (argc < 3) {
  42.         printf("Usage: ./yourprog directory max_size\n");
  43.         return 0;
  44.     }
  45.  
  46.     const char* dir_path = argv[1];
  47.     off_t max_size = atoll(argv[2]);
  48.  
  49.     print_regular_files(dir_path, 0, max_size);
  50.  
  51.     return 0;
  52. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement