hawxgamer

verzeichnisbaum

Dec 2nd, 2013
100
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.43 KB | None | 0 0
  1. #include <string.h>
  2. #include <limits.h>
  3. #include <dirent.h>
  4. #include <stdlib.h>
  5. #include <stdio.h>
  6.  
  7.  
  8. void writer(int level){
  9.  
  10.   const char characters[] = "|   ";
  11.  unsigned int length=strlen(characters)*(level+1);
  12.     char postfix[length];
  13.     memset( postfix, '\0', sizeof(char)*length );
  14.  
  15.  
  16.  
  17.     for(level;level>0;level--)
  18.     strcat(postfix, characters);
  19.     printf("%s", postfix);
  20. }
  21.  
  22.  
  23. void tree(char *path, int level)
  24. {
  25.  
  26.     struct dirent *direntry;
  27.     DIR *directory;
  28.  
  29.  
  30.  
  31.     chdir(path);  //in neues Verzeichnis wechseln
  32.  
  33.     directory=opendir(".");
  34.  
  35.     if(directory)
  36.     {
  37.  
  38.         while((direntry=readdir(directory)) != 0)
  39.         {
  40.  
  41.             if(strcmp(direntry->d_name, ".") != 0 && strcmp(direntry->d_name, "..") != 0)
  42.             {
  43.             if(strlen(direntry->d_name)>PATH_MAX)
  44.             printf("path name is too long\n");
  45.  
  46.                 if(direntry->d_type==DT_DIR)
  47.                 {
  48.                 writer(level+1);
  49.                     printf("|---[%s]\n",direntry->d_name );
  50.                     tree(direntry->d_name,level+1);
  51.                 }
  52.                 else
  53.                 writer(level);
  54.                     printf("|---[%s]\n", direntry->d_name );
  55.             }
  56.         }
  57.         closedir(directory);
  58.     }
  59.  
  60. }
  61.  
  62.  
  63. int main(int argc, char const *argv[])
  64. {
  65.     DIR *dir;
  66.     char *path;
  67.  
  68.     path=argv[1];
  69.  
  70.     if(path==0)  //wenn nichts angegben wurde dann
  71.         path=".";  //wähle aktuelles Verzeichnis
  72.  
  73.     dir=opendir(path);
  74.  
  75.     if(dir!=0)
  76.     {
  77.         tree(path,0);
  78.     }
  79.     else
  80.     {
  81.         printf("%s is a wrong directory name\n", argv[1]);
  82.         return EXIT_FAILURE;
  83.     }
  84.  
  85.     return EXIT_SUCCESS;
  86. }
Advertisement
Add Comment
Please, Sign In to add comment