现在的位置: 首页 > 综合 > 正文

linux 文件遍历

2013年03月22日 ⁄ 综合 ⁄ 共 643字 ⁄ 字号 评论关闭
#include <iostream>
#include <sys/types.h>
#include <dirent.h>

using namespace std;

void traverse(const string &dirname);
int main()
{
       string path;
       cin>>path;
       traverse(path);
       
       return 0;
 }

void traverse(const string &dirname)
{
        if (DIR *dir = opendir(dirname.c_str()))
        {
                while (struct dirent *entry = readdir(dir))
                {
                        if (strcmp(entry->d_name, ".") == 0)
                                continue;
                        if (strcmp(entry->d_name, "..") == 0)
                                continue;

                        std::string filename = dirname + entry->d_name;
                        if ((entry->d_type & DT_DIR) == DT_DIR && !((entry->d_type & DT_LNK) == DT_LNK))
                        {
                                string dirname = filename + "/";
                                traverse(dirname);
                        }
                        else if ((entry->d_type & DT_REG) == DT_REG)
                        {
                                cout << filename << endl;
                        }
                }

                closedir(dir);
        }
}

ref: http://www.cplusplus.com/forum/general/56110/

抱歉!评论已关闭.