12. Directory walk

Make directory 12_Permissions and cd there.

  1. On filename patterns:
    • Special characters: «*», «?», «[characters]»:

         1 $ ls /usr/bin/no*
         2 /usr/bin/nohup    /usr/bin/nosetests3   /usr/bin/nosetests-3.7
         3 /usr/bin/nomarch  /usr/bin/nosetests-3
         4 $ ls /usr/bin/n?c*
         5 /usr/bin/nick2ldif  /usr/bin/nmcli
         6 $ ls /usr/bin/n[a-e]*
         7 /usr/bin/namei    /usr/bin/ncdu                /usr/bin/neqn           /usr/bin/newgrp
         8 /usr/bin/nano     /usr/bin/ncurses5-config     /usr/bin/net
         9 /usr/bin/natspec  /usr/bin/ndg_httpclient.py3  /usr/bin/netcat
        10 /usr/bin/nc       /usr/bin/neotoppm            /usr/bin/netpbm-config
        11 $ ls /usr/bin/n[a-ex]*
        12 /usr/bin/namei    /usr/bin/ncdu                /usr/bin/neqn           /usr/bin/newgrp
        13 /usr/bin/nano     /usr/bin/ncurses5-config     /usr/bin/net            /usr/bin/nxproxy
        14 /usr/bin/natspec  /usr/bin/ndg_httpclient.py3  /usr/bin/netcat
        15 /usr/bin/nc       /usr/bin/neotoppm            /usr/bin/netpbm-config
        16 
      
    • see glob for more

  2. Write a program that uses unlink to remove files:

    • ./deletefile file1 file2 …

  3. Write a program than uses opendir, readdir and closedir to list a directory content

    • ./lsdir /usr/share/dict

    • ./lsdir .

    • modify this program to show file object type (using dirent->d_type as documented in readdir)

  4. Copy this program to a new one, lsdir2.c an modify it:

    • define a function listdir(char *path) that performs all the listing and refactor the code:

         1 
         2   int main(int argc, char *argv[]) {
         3         listdir(argv[1]);
         4         return 0;
         5 }
      
    • filter out «"."» and «".."» directory entries

      • e. g (suppose we are in while(…readdir()…) cycle):

           1                 if(!strcmp(dirent->d_name, ".") || !strcmp(dirent->d_name, ".."))
           2                         continue;
        
    • check every next file object to be a directory (see readdir) and mention this

      • e. g.
           1                 if(dirent->d_type == DT_DIR)
           2                         printf("%s: directory\n", dirent->d_name);
           3                 else
           4                         printf("%s: %d\n", dirent->d_name, dirent->d_type);
        
  5. Copy this program to a new one, lsdir3.c an modify it:

    • to accept two parameters: a directory and a pattern

    • display only entries that apply the pattern via fnmatch

    • e. g. ./lsdir3 dir "fil*.1?" for matching fil.11, files.01.1a but not file11 nor files.01.1bc

      • Note «"…"» around the pattern

  • Recursive listing was removed from tasks, because it requires non-trivial string operations

H/W

HSE/ProgrammingOS/Lab_12_DirectoryWalk (последним исправлял пользователь FrBrGeorge 2020-03-05 10:52:28)