Advertisement
Rishana

RM_L2_update

Feb 22nd, 2020
93
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.81 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <sys/types.h>
  3. #include <unistd.h>
  4. #include <dirent.h>
  5. #include <string.h>
  6. #include <stdlib.h>
  7.  
  8. int extensionsMatch(char *fileName, char *extension)
  9. {
  10.     size_t fileNameLen = strlen(fileName),
  11.         extensionLen = strlen(extension);
  12.  
  13.     if (fileNameLen > extensionLen && fileName[fileNameLen - extensionLen - 1] == '.')
  14.     {
  15.         for (size_t i = 1; i <= extensionLen; i++)
  16.             if (extension[extensionLen - i] != fileName[fileNameLen - i])
  17.                 return 0;
  18.         return 1;
  19.     }
  20.     return 0;
  21. }
  22.  
  23. int main(int argc, char **argv)
  24. {
  25.     DIR *currDir = NULL;
  26.     struct dirent *currFile = NULL;
  27.     ino_t currDescIndex = 0, parentDescIndex = 0;
  28.     size_t filesNum = 0;
  29.  
  30.     if (argc != 2)
  31.     {
  32.         printf("Error: should be only one argument [file extension]\n");
  33.         exit(EXIT_FAILURE);
  34.     }
  35.  
  36.     printf("Search for files with extension '%s'...\n", argv[1]);
  37.  
  38.     do
  39.     {
  40.         if (!(currDir = opendir("./")))
  41.         {
  42.             printf("Error opening directory\n");
  43.             exit(EXIT_FAILURE);
  44.         }
  45.  
  46.         while (currFile = readdir(currDir))
  47.         {
  48.             if (currFile->d_name[0] == '.')
  49.             {
  50.                 if (currFile->d_name[1] == '.')
  51.                     parentDescIndex = currFile->d_ino;
  52.                 else if (currFile->d_name[1] == '\0')
  53.                     currDescIndex = currFile->d_ino;
  54.             }
  55.  
  56.             if (extensionsMatch(currFile->d_name, argv[1]))
  57.             {
  58.                 printf("%s\n", currFile->d_name);
  59.                 filesNum++;
  60.             }
  61.         }
  62.  
  63.         chdir("..");
  64.         closedir(currDir);
  65.  
  66.     } while (currDescIndex != parentDescIndex);
  67.  
  68.     if (!filesNum)
  69.         printf("There's no files with this extension\n");
  70.  
  71.     return 0;
  72. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement