分享

C++获取目录下的文件列表

 勤奋不止 2013-08-27
#include   <iostream>  
#include   
<io.h>  
#include   
<direct.h>  
#include   
<string>  
#include   
<vector>  
#include   
<iomanip>  
#include   
<ctime>  
using   namespace   std;  

void getFiles( string, vector<string>& );

int   main()  {  
    vector
<string>   files;  

    getFiles( 
".", files );

    
// print the files get
    for   (int   j=0;   j<files.size();   ++j)  {
        cout   
<<   files[j] << endl; 
    }

        
    
return   0;  
}


void getFiles( string path, vector<string>& files ) {
    
//文件句柄  
    long   hFile   =   0;  
    
//文件信息  
    struct _finddata_t fileinfo;  

    
string p;

    
if   ((hFile   =   _findfirst(p.assign(path).append("/*").c_str(),&fileinfo))   !=   -1)  {  

        
do  {  
            
//如果是目录,迭代之
            
//如果不是,加入列表
            if   ((fileinfo.attrib   &   _A_SUBDIR)) {  
                
if   (strcmp(fileinfo.name,".")   !=   0   &&   strcmp(fileinfo.name,"..")   !=   0)  
                    getFiles(   p.assign(path).append(
"/").append(fileinfo.name), files   );  
            }
  else  {  
                files.push_back(   p.assign(path).append(
"/").append(fileinfo.name)  );
            }
  
        }
   while   (_findnext(   hFile,   &fileinfo   )   ==   0);  

        _findclose(hFile);  
    }

}

这是不影响当前目录的,
我看行,
网上有的是用了 _chdir 方法的,影响了当前程序状态,
也就是说,有的方法在用的时候你如果新建一个相对路径的话, 位置会不对,
而这个不会.

    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多