在Linux下,用 c++ 遍历目录下的所有文件比较简单,代码如下,有需要的可以参考~
#include
#include
#include
#include
#include
#include
#include
using namespace std;
/***** Global Variables *****/
char dir[100] = "/home";
int const MAX_STR_LEN = 200;
/* Show all files under dir_name , do not show directories ! */
void showAllFiles( const char * dir_name )
{
// check the parameter !
if( NULL == dir_name )
{
cout<
return;
}
// check if dir_name is a valid dir
struct stat s;
lstat( dir_name , &s );
if( ! S_ISDIR( s.st_mode ) )
{
cout<
return;
}
struct dirent * filename; // return value for readdir()
DIR * dir; // return value for opendir()
dir = opendir( dir_name );
if( NULL == dir )
{
cout<
return;
}
cout<
/* read all the files in the dir ~ */
while( ( filename = readdir(dir) ) != NULL )
{
// get rid of "." and ".."
if( strcmp( filename->d_name , "." ) == 0 ||
strcmp( filename->d_name , "..") == 0 )
continue;
cout<d_name <
}
}
int main()
{
// 测试
showAllFiles( dir );
return 0;
}