Advertisement
STANAANDREY

so2 nth char from each file in a dir

Oct 18th, 2024
90
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 2.14 KB | None | 0 0
  1. #include <stdlib.h>
  2. #include <stdio.h>
  3. #include <sys/types.h>
  4. #include <dirent.h>
  5. #include <string.h>
  6. #include <sys/stat.h>
  7. #include <unistd.h>
  8. #include <fcntl.h>
  9.  
  10. #define BUFF_SIZE (1 << 10)
  11.  
  12. void printNthChar(const char path[], int n) {
  13.     int fd = open(path, O_RDONLY);
  14.     if (fd < 0) {
  15.         perror("");
  16.         exit(1);
  17.     }
  18.    
  19.     char buffer[BUFF_SIZE];
  20.     int totalRead = 0, bytesRead, ok = 0;
  21.     while ((bytesRead = read(fd, buffer, BUFF_SIZE)) > 0) {
  22.         for (ssize_t i = 0; i < bytesRead; ++i) {
  23.             totalRead++;
  24.             if (totalRead == n) {
  25.                 printf("The %d-th character is: '%c'\n", n, buffer[i]);
  26.                 ok = 1;
  27.                 break;
  28.             }
  29.         }
  30.         if (ok) {
  31.             break;
  32.         }
  33.     }
  34.  
  35.     if (bytesRead == -1) {
  36.         perror("");
  37.         exit(1);
  38.     }
  39.  
  40.     if (close(fd)) {
  41.         perror("close");
  42.     }
  43. }
  44.  
  45. void iterateDir(const char path[], int n) {
  46.     DIR *dir = opendir(path);
  47.     if (dir == NULL) {
  48.         perror("");
  49.         exit(1);
  50.     }
  51.  
  52.     for (struct dirent *dep; (dep = readdir(dir)) != NULL;) {
  53.         const char *const dName = dep->d_name;
  54.         if (!strcmp(dName, ".") || !strcmp(dName, "..")) {
  55.             continue;
  56.         }
  57.         char absPath[BUFF_SIZE];
  58.         sprintf(absPath, "%s/%s", path, dName);
  59.  
  60.         struct stat statBuff;
  61.         if (lstat(absPath, &statBuff)) {
  62.             perror("");
  63.             exit(1);
  64.         }
  65.  
  66.         const mode_t mode = statBuff.st_mode;
  67.         if (S_ISDIR(mode)) {
  68.             iterateDir(absPath, n);
  69.         } else if (S_ISREG(mode)) {
  70.             printf("%s\n", absPath);
  71.             off_t size = statBuff.st_size;
  72.             if (size < n) {
  73.                 puts("OUT_OF_BOUNDS!");
  74.             } else {
  75.                 printNthChar(absPath, n);
  76.             }
  77.         }
  78.     }
  79.  
  80.     if (closedir(dir) != 0) {
  81.         perror("closedir");
  82.     }
  83. }
  84.  
  85. int main(int argc, char *argv[]) {
  86.     if (argc != 3) {
  87.         fprintf(stderr, "Wrong usage!\n");
  88.         exit(1);
  89.     }
  90.     int n = atoi(argv[2]);
  91.     iterateDir(argv[1], n);
  92.     return 0;
  93. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement