Advertisement
candale

Fast ls on huge number of files in directory, Linux

Nov 1st, 2021
881
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.22 KB | None | 0 0
  1. #define _GNU_SOURCE
  2. #include <dirent.h>     /* Defines DT_* constants */
  3. #include <fcntl.h>
  4. #include <stdio.h>
  5. #include <unistd.h>
  6. #include <stdlib.h>
  7. #include <string.h>
  8. #include <sys/stat.h>
  9. #include <sys/syscall.h>
  10.  
  11. #define handle_error(msg) \
  12.        do { perror(msg); exit(EXIT_FAILURE); } while (0)
  13.  
  14. struct linux_dirent {
  15.    long           d_ino;
  16.    off_t          d_off;
  17.    unsigned short d_reclen;
  18.    char           d_name[];
  19. };
  20.  
  21. #define BUF_SIZE 1024*1024*7
  22.  
  23. int
  24. main(int argc, char *argv[])
  25. {
  26.    int fd, nread;
  27.    char buf[BUF_SIZE];
  28.    struct linux_dirent *d;
  29.    int bpos;
  30.    char d_type;
  31.  
  32.    fd = open(argc > 1 ? argv[1] : ".", O_RDONLY | O_DIRECTORY);
  33.    if (fd == -1)
  34.        handle_error("open");
  35.  
  36.    for ( ; ; ) {
  37.        nread = syscall(SYS_getdents, fd, buf, BUF_SIZE);
  38.        if (nread == -1)
  39.            handle_error("getdents");
  40.  
  41.        if (nread == 0)
  42.            break;
  43.  
  44.        for (bpos = 0; bpos < nread;) {
  45.            d = (struct linux_dirent *) (buf + bpos);
  46.            if(d->d_ino != 0 && strcmp(d->d_name, ".") != 0 && strcmp(d->d_name, "..") != 0) {
  47.               printf("%s\n", d->d_name);
  48.            }
  49.            bpos += d->d_reclen;
  50.        }
  51.    }
  52.  
  53.    exit(EXIT_SUCCESS);
  54. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement