Linux下 C++遍历目录下所有文件

来源:互联网 发布:中国人才流失知乎 编辑:程序博客网 时间:2024/06/06 04:27

      在Linux下,用 c++ 遍历目录下的所有文件比较简单,代码如下,有需要的可以参考~

#include <iostream>#include <stdio.h>#include <unistd.h>#include <dirent.h>#include <stdlib.h>#include <sys/stat.h>#include <string.h>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<<" dir_name is null ! "<<endl;return;}// check if dir_name is a valid dirstruct stat s;lstat( dir_name , &s );if( ! S_ISDIR( s.st_mode ) ){cout<<"dir_name is not a valid directory !"<<endl;return;}struct dirent * filename;    // return value for readdir() DIR * dir;                   // return value for opendir()dir = opendir( dir_name );if( NULL == dir ){cout<<"Can not open dir "<<dir_name<<endl;return;}cout<<"Successfully opened the dir !"<<endl;/* 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<<filename ->d_name <<endl;}} int main(){// 测试showAllFiles( dir );return 0;}


0 0
原创粉丝点击