我接到了一项任务,要求我们对给定目录中的所有文件执行某些操作。对于遇到的每个目录,我们应该 fork 出我们程序的另一个实例。我最初的方法是使用 opendir()
和 readdir()
,但我发现 readdir()
正在枚举 目录中的所有条目(不仅仅是顶级项目),因此一些条目将被处理多次(一次由父进程处理,一次由每个子进程处理,直到文件位于“根”)。例如,给定以下文件系统树:
.
├── 1.txt
├── a
│ ├── 2.txt
│ ├── 3.txt
│ └── c
│ └── 4.txt
└── b
└── 5.txt
如果我在 .
上调用我的程序,它将处理 1.txt
,并创建两个子进程,一个分别用于 a
和b
然后等待这些进程完成。
第一个子进程在 2.txt
和 3.txt
上工作,并为 c
创建另一个子进程。
第三个子进程在 5.txt
上运行
简单地说:我不知道如何只读取目录的一级
我可以继续使用最初的方法,但我觉得忽略不在我当前正在检查的直接文件夹中的所有内容真的效率很低。
编辑 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;
}
最佳答案
那么让我们假设您使用 dirent 并且有一个类似于以下教程的代码:http://www.dreamincode.net/forums/topic/59943-accessing-directories-in-cc-part-i/
你必须通过d_type来区分dirent结构提供的文件和目录。
看这里:http://www.gnu.org/software/libc/manual/html_node/Directory-Entries.html
这样就可以让他只列出一个目录下的文件。
关于c++ - 在 Unix C++ 中列出文件夹根目录中的文件和目录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39422501/