C traverse the directory and its subdirectories

A directory traversal, access to an array of all the files in the directory path

. 1 #include <the iostream>
 2 #include <dirent.h>
 . 3 #include <Vector>
 . 4  
. 5  void listdir ( char * path, STD :: Vector <STD :: String > * Files)
 . 6  {
 . 7      the DIR * directory_pointer;
 . 8      struct dirent * entry;
 . 9      char childpath [ 512 ];   // define an array of characters, used to store the read path 
10      char filepath [ 512 ];   // define an array of characters, used to store the read path 
. 11      directory_pointer = opendir (path);
12 is      Memset (childpath, 0 , the sizeof (childpath)); // the array element of the array of characters all zero childpath 
13 is      the while ((entry = the readdir (directory_pointer)) = NULL!)   // read pDir open directory, and assigned to ENT, while determining whether the directory is empty, not empty the loop is executed 
14      {
 15          IF (entry-> d_type & DT_DIR)   // read open the directory file and the type of arithmetic operation and bit with DT_DIR, i.e., if d_type type read is DT_DIR (= 4 read directory table) 
16          {
 . 17              IF (strcmp (entry-> d_name, " . " ) == 0 || strcmp (entry-> d_name, " .. " ) == 0 )
 18             {
 19                  // if d_name .. or read is represented in the current directory is read on a symbol and directory symbols, with contiue skipped, the following output is not performed. 
20 is                  Continue ;
 21 is              }
 22 is              
23 is              sprintf (childpath, " S% / S% " , path, entry-> d_name);   // if non .. path and file name will be paid d_name childpath, and outputs the next line printf.
 24              // the printf (" path:% S \ n- ", childpath); 
25              listdir (childpath, Files);   // recursive directory read word content lower, because it is recursive, so that all output sequentially from the outside inwards directory (directory name + path),
 26              // before the else out sequentially outputted from the all file names 
27          }
 28          else   //If the type is not read d_type DT_DIR, i.e., the read is not a directory, but the file, d_name output directly, i.e., the output file name 
29          {
 30              sprintf (filepath, " % S /% S " , path, entry-> d_name );
 31 is              the printf ( " file path:% S \ n- " , filepath); // output filename directory belt 
32              Files-> push_back (filepath);
 33 is          }
 34 is      }
 35  }
 36  
37 [  int main ( int argc, const  char * the argv []) {
 38 is      // INSERT code here Wallpaper ...
39     std::cout << "ListFile Start!\n";
40     
41     std::string res = "res";
42     char *path = const_cast<char *>(res.c_str());
43     std::vector<std::string> files;
44     listDir(path, &files);
45     return 0;
46 }

operation result:

 

 

Guess you like

Origin www.cnblogs.com/ring1992/p/11865579.html