列出Unix c++中文件夹根目录下的文件和目录
List files and directories in the root of a folder in Unix C++
我被分配了一个任务,要求我们对给定目录下的所有文件做一些事情。对于遇到的每个目录,我们应该派生出程序的另一个实例。我最初的方法使用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
上工作
简单地说:我不知道如何读取目录的一个级别
我可以继续使用我最初的方法,但我觉得它会真的忽略所有不在我当前检查的直接文件夹中的内容。
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
这样你可以让他只列出一个目录下的文件。
相关文章:
- .cpp和.h文件中的模板专用化声明
- 为什么两个不同的未命名名称空间可以共存于一个cpp文件中
- 文本文件中的单词链表
- CMake-按正确顺序将项目与C运行时对象文件链接
- 使用新行和不使用新行读取文件
- 在C++程序中输入的文本文件将不起作用,除非文本被复制和粘贴
- 挂起和取消挂起一个文件DLL
- 如何确定我已使用非编码文件到达 EOF?
- 命名空间中具有.h和.cpp文件的类
- 如何使用ndk-build.cmd构建Android.so文件
- 从包含m行的文件中提取n行,必要时(惰性地)重复该文件
- 读取文件并输入到矢量中
- 在C++中查找文件
- c++库的公共头文件中应该包含什么
- 如何获取cmake工具链文件中的项目根目录,这可能吗
- 项目根目录中的生成文件 "no Input Files"
- c++:将文件复制到Windows下的根目录
- 列出Unix c++中文件夹根目录下的文件和目录
- C++正在将DLL从根目录移到visual studio的子文件夹中
- 如何用不在根目录中的文件构建GNU全局标记文件?