training

Code I wrote during training
git clone git://git.bitsmanent.org/training
Log | Files | Refs | README

ex-4.19.c (1243B)


      1 /*
      2  * Advanced Programming in the UNIX(r) Environment
      3  *
      4  * Exercise 4.19
      5  *
      6  * NOTE: the exercise is done assuming PATH_MAX already defined
      7 */
      8 
      9 #include <stdio.h>
     10 #include <stdlib.h>
     11 #include <sys/stat.h>
     12 #include <unistd.h>
     13 #include <limits.h>
     14 
     15 #define DIRNAME	"ex-4.19_dir"
     16 
     17 int
     18 main(void)
     19 {
     20    int i, levels, umask_save;
     21    char cwd[PATH_MAX * 2] = { 0 };
     22 
     23    umask_save = umask(0); /* Store the umask value and clear the mask */
     24 
     25    levels = PATH_MAX / sizeof(DIRNAME) + 1;
     26 
     27    printf("Creating a %d-levels deep directories tree..", levels);
     28    fflush(stdout);
     29 
     30    /* Create a deep directories tree */
     31    for(i = 0; i < levels; i++) {
     32 
     33       /* Create the directory */
     34       if( mkdir(DIRNAME, 0700) == -1 ) {
     35          perror("\nmkdir");
     36 	 break;
     37       }
     38 
     39       /* Enter the directory */
     40       if( chdir(DIRNAME) == -1 ) {
     41          perror("\nchdir");
     42 	 break;
     43       }
     44 
     45    }
     46 
     47    /* Get the working directory on the leaf directory */
     48    if( getcwd(cwd, sizeof(cwd)) == NULL ) {
     49       perror("\ngetcwd");
     50       printf("\tdirectory: %d; full path length: %d\n", i, sizeof(DIRNAME)*i);
     51    }
     52 
     53    printf(" done\n");
     54 
     55    (void)umask(umask_save); /* Restore the umask value (pretty useless here) */
     56    
     57    return EXIT_SUCCESS;
     58 } /* eof main() */
     59