c ++列出(LINUX)中的所有目录和子目录 [英] c++ list all directories and subdirectories within in (LINUX )

查看:415
本文介绍了c ++列出(LINUX)中的所有目录和子目录的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是c ++的新手。有人可以给我一些如何在LINUX中递归获取所有目录及其子目录的代码。我还没有在互联网上找到任何可以帮助我(或代码正常工作)的东西。我需要使用文件夹及其子文件夹来获取所有文件。

I am new in c ++ . could someone please give me some code of how to get all directories and all it's subdirectories RECURSIVELY in LINUX. i haven't found anything on internet that could help me ( or code that works.) I need to get all files withing folder and it;s subfolder.

在UBUNTU我没有getfiles,目录...

IN UBUNTU I don't have getfiles, directories...

推荐答案

在Linux上尝试一下:

Try this on Linux:

#include <iostream>
#include <string>
#include <dirent.h>

void ProcessDirectory(std::string directory);
void ProcessFile(std::string file);
void ProcessEntity(struct dirent* entity);

std::string path = "/path/to/directory/";

int main()
{
    std::string directory = "theDirectoryYouWant";
    ProcessDirectory(directory);    

    return 0;
}

void ProcessDirectory(std::string directory)
{
    std::string dirToOpen = path + directory;
    auto dir = opendir(dirToOpen.c_str());

    //set the new path for the content of the directory
    path = dirToOpen + "/";

    std::cout << "Process directory: " << dirToOpen.c_str() << std::endl;

    if(NULL == dir)
    {
        std::cout << "could not open directory: " << dirToOpen.c_str() << std::endl;
        return;
    }

    auto entity = readdir(dir);

    while(entity != NULL)
    {
        ProcessEntity(entity);
        entity = readdir(dir);
    }

    //we finished with the directory so remove it from the path
    path.resize(path.length() - 1 - directory.length());
    closedir(dir);
}

void ProcessEntity(struct dirent* entity)
{
    //find entity type
    if(entity->d_type == DT_DIR)
    {//it's an direcotry
        //don't process the  '..' and the '.' directories
        if(entity->d_name[0] == '.')
        {
            return;
        }

        //it's an directory so process it
        ProcessDirectory(std::string(entity->d_name));
        return;
    }

    if(entity->d_type == DT_REG)
    {//regular file
        ProcessFile(std::string(entity->d_name));
        return;
    }

    //there are some other types
    //read here http://linux.die.net/man/3/readdir
    std::cout << "Not a file or directory: " << entity->d_name << std::endl;
}

void ProcessFile(std::string file)
{
    std::cout << "Process file     : " << fileToOpen.c_str() << std::endl;

    //if you want to do something with the file add your code here
}

这篇关于c ++列出(LINUX)中的所有目录和子目录的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆