-
Notifications
You must be signed in to change notification settings - Fork 0
/
list_file.cpp
59 lines (50 loc) · 1.32 KB
/
list_file.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
#include <regex.h>
#include <dirent.h>
#include <vector>
/**
* 列出指定文件夹下符合指定模式的所有文件
* @param filter_pattern 示例 ^aimdb.*bin$
*/
int list_file(const char *path, const char *filter_pattern, std::vector<std::string> &files)
{
regex_t reg;
if (filter_pattern)
{
const int res = regcomp(®, filter_pattern, REG_NOSUB);
if (res)
{
char errbuf[256];
regerror(res, ®, errbuf, sizeof(errbuf));
MLOG_ERROR("regcomp return error. filter pattern %s. errmsg %d:%s",
filter_pattern, res, errbuf);
return -1;
}
}
DIR *pdir = opendir(path);
if (!pdir)
{
if (filter_pattern)
regfree(®);
MLOG_ERROR("open directory failure. path %s, errmsg %d:%s",
path, errno, strerror(errno));
return -1;
}
files.clear();
struct dirent entry;
struct dirent * pentry = NULL;
char tmp_path[PATH_MAX];
while((0 == readdir_r(pdir, &entry, &pentry)) && (NULL != pentry))
{
if ('.' == entry.d_name[0]) // 跳过./..文件和隐藏文件
continue;
snprintf(tmp_path, sizeof(tmp_path), "%s/%s", path, entry.d_name);
if (is_dir(tmp_path))
continue;
if (!filter_pattern || 0 == regexec(®, entry.d_name, 0, NULL, 0))
files.push_back(entry.d_name);
}
if (filter_pattern)
regfree(®);
sort(files.begin(), files.end(), binlog_cmp);
return files.size();
}