列出Unix c++中文件夹根目录下的文件和目录

List files and directories in the root of a folder in Unix C++

本文关键字:文件 根目录 Unix c++ 中文 文件夹 列出      更新时间:2023-10-16

我被分配了一个任务,要求我们对给定目录下的所有文件做一些事情。对于遇到的每个目录,我们应该派生出程序的另一个实例。我最初的方法使用opendir()readdir(),但我发现readdir()枚举目录中的所有条目(不仅仅是顶级条目),因此一些条目将被处理多次(一次由父进程处理,一次为每个子进程处理,直到文件位于"根")。例如,给定以下文件系统树:

.
├── 1.txt
├── a
│   ├── 2.txt
│   ├── 3.txt
│   └── c
│       └── 4.txt
└── b
    └── 5.txt

如果我在.上调用我的程序,它将处理1.txt,并创建两个子进程,ab各一个,然后等待这些进程完成。

第一个子进程在2.txt3.txt上工作,并为c创建另一个子进程。

第三个子进程在5.txt上工作

简单地说:我不知道如何读取目录的一个级别

我可以继续使用我最初的方法,但我觉得它会真的忽略所有不在我当前检查的直接文件夹中的内容。


EDIT 1:示例代码:

int process(std::string binpath, std::string src)
{
        DIR* root = nullptr;
        root = opendir(source.c_str());
        if(root == nullptr)
        {
            return -1;
        }
        struct dirent* details;
        struct stat file;
        std::string path;
        std::queue<int> childPids;
        bool error = false;
        while((details = readdir(root)) != nullptr)
        {
            path = source + details->d_name;
            lstat(path.c_str(), &file);
            if(IsDirectory(file.st_mode))
            {
                if(strcmp(details->d_name, ".") == 0 || strcmp(details->d_name, "..") == 0)
                {
                    continue;
                }
                // Fork and spawn new process and remember child pid
                auto pid = fork();
                if(pid == 0)
                {
                    char* args[] = {
                            (char*) "-q",
                            (char*)"-s", const_cast<char*>(path.c_str()),
                            NULL
                    };
                    char* env[] = {NULL};
                    execve(binpath.c_str(), args, env);
                }
                else
                {
                    childPids.push(pid);
                }
            }
            else
            {
                if(!DoWorkOnFile(path)) error = true;
            }
        }
        //Wait all child pids
        while(!childPids.empty())
        {
            auto pid = childPids.front();
            int status;
            if(waitpid(pid, &status, 0) == pid)
            {
                if(status != 0) error = true;
            }
            else
            {
                error = true;
            }
            childPids.pop();
        }
        closedir(root);
        return error ? -1 : 0;
}

那么让我们假设您使用dient,并有如下教程中的代码:http://www.dreamincode.net/forums/topic/59943-accessing-directories-in-cc-part-i/

你必须区分文件和目录,它们是由d_type提供的不同结构体。

看这里:http://www.gnu.org/software/libc/manual/html_node/Directory-Entries.html

这样你可以让他只列出一个目录下的文件。