C++遍历文件夹函数

 1 #include <iostream>
 2 #include <fstream>
 3 #include <string.h>
 4 #include <vector>
 5 #include <sys/io.h>
 6 #include <dirent.h>
 7 #include <stdlib.h>
 8 #include <sys/stat.h>
 9 #include "tools.hpp"
10 
11 //遍历文件夹
12 void showAllFiles(const char * dir_name,vector<string> &files )
13 {
14     // check the parameter !
15     if( NULL == dir_name )
16     {
17         cout<<" dir_name is null ! "<<endl;
18         return;
19     }
20  
21     // check if dir_name is a valid dir
22     struct stat s;
23     lstat( dir_name , &s );
24     if( ! S_ISDIR( s.st_mode ) )
25     {
26         cout<<"dir_name is not a valid directory !"<<endl;
27         return;
28     }
29     
30     struct dirent * filename;    // return value for readdir()
31      DIR * dir;                   // return value for opendir()
32     dir = opendir( dir_name );
33     if( NULL == dir )
34     {
35         cout<<"Can not open dir "<<dir_name<<endl;
36         return;
37     }
38     cout<<"Successfully opened the dir !"<<endl;
39     
40     /* read all the files in the dir ~ */
41     while( ( filename = readdir(dir) ) != NULL )
42     {
43         // get rid of "." and ".."
44         if( strcmp( filename->d_name , "." ) == 0 || 
45             strcmp( filename->d_name , "..") == 0    )
46             continue;
47         files.push_back(filename->d_name);
48     }
49 } 

猜你喜欢

转载自www.cnblogs.com/buyizhiyou/p/12744611.html