Waz*_*azy 3 c++ filesystems directory
我试图通过c ++为unix OS获取目录中的文件数量
我有这个代码
int i;
i = (int)system("ls -l /root/opencv/*.png|wc -l");
cout << "Number of files " << i << endl;
Run Code Online (Sandbox Code Playgroud)
但我得到了输出
21
Number of files 0
Run Code Online (Sandbox Code Playgroud)
我怎样才能21在i
通过使用glob(2)函数可以非常轻松地实现您想要的:
#include <glob.h>
int glob(const char *pattern, int flags,
int (*errfunc) (const char *epath, int eerrno),
glob_t *pglob);
Run Code Online (Sandbox Code Playgroud)
简单的例子(没有错误处理):
glob_t gl;
size_t num = 0;
if(glob("/root/opencv/*.png", GLOB_NOSORT, NULL, &gl) == 0)
num = gl.gl_pathc;
globfree(&gl);
cout << "Number of files: " << num << endl;
Run Code Online (Sandbox Code Playgroud)
虽然您指定了OS,但可能需要使用便携式解决方案.
你正在寻找Boost :: Filesystems directory_iterator和std :: count_if.谓词count_if可以使用,也可以std::regex是适合你的任何东西.
这是展示所需行为的最小示例(不包括递归):
#include <boost/filesystem.hpp>
#include <iostream>
#include <algorithm>
namespace fs = boost::filesystem;
int main()
{
int i = std::count_if(fs::directory_iterator("/your/path/here/"),
fs::directory_iterator(),
[](const fs::directory_entry& e) {
return e.path().extension() == ".png"; });
//also consider recursive_directory_iterator
std::cout << i << std::endl;
return 0;
}
Run Code Online (Sandbox Code Playgroud)