【发布时间】:2021-04-24 03:37:58
【问题描述】:
当前代码 sn-p 将匹配模式并列出所有匹配模式文件存在于指定目录中,下面的示例 文件 是要匹配的模式* ,这里的输出将列出如下的绝对路径。
/home/downloads/File1
/home/downloads/File2
/home/downloads/File3
/home/downloads/File4
其中,我只查找要列出的文件名,即如下所示:
File1
File2
File3
File4
c++代码如下:
#include <glob.h>
#include <cerrno>
#include <cstring>
#include <iostream>
#include <stdexcept>
#include <string>
#include <vector>
using namespace std;
vector<string> glob(const string& pattern) {
glob_t glob_result = {0}; // zero initialize
// do the glob operation
int return_value = ::glob(pattern.c_str(), GLOB_TILDE, NULL, &glob_result);
if(return_value != 0) throw runtime_error(strerror(errno));
// collect all the filenames into a std::vector<std::string>
// using the vector constructor that takes two iterators
vector<string> filenames(
glob_result.gl_pathv, glob_result.gl_pathv + glob_result.gl_pathc);
// cleanup
globfree(&glob_result);
// done
return filenames;
}
int main() {
try { // catch exceptions
vector<string> res = glob("/home/downloads/File*"); // files with an "File" in the filename
for(size_t i = 0; i< res.size(); ++i)
std::cout << res[i] << '\n';
} catch(const exception& ex) {
cerr << ex.what() << endl;
}
}
【问题讨论】:
标签: c++ linux string vector absolute-path