[英]In C, checking for existence of file with name matching a pattern
I've seen a few methods for checking the existence of a file in C. However, everything I've seen works for a specific file name. 我已经看到了几种检查C中文件是否存在的方法。但是,我所看到的所有内容都适用于特定的文件名。 I would like to check for any file that matches a particular pattern.
我想检查是否有匹配特定模式的文件。 For instance, maybe the pattern is "lockfile*" and "lockfileA", "lockfile.txt", or "lockfile.abc" would register in the check.
例如,模式可能是“ lockfile *”,而“ lockfileA”,“ lockfile.txt”或“ lockfile.abc”将在支票中注册。 The way I am doing this currently is to open the directory with opendir() then cycle through readdir() and try to match the pattern with name of each file returned.
我目前正在执行的方法是使用opendir()打开目录,然后遍历readdir()并尝试将模式与返回的每个文件的名称匹配。 It works, but I sure would like a more compact way to do this.
它可以工作,但是我确定想要一种更紧凑的方法。 Any ideas?
有任何想法吗?
You can use glob(3) (standardized by POSIX). 您可以使用glob(3) (由POSIX标准化)。 You give it a wildcard pattern and it will search the filesystem for matches.
给它一个通配符模式,它将在文件系统中搜索匹配项。
Example: 例:
#include <glob.h>
#include <stdio.h>
int main(int argc, char **argv)
{
glob_t globbuf;
if (0==glob(argv[1], 0, NULL, &globbuf)){
char **a=globbuf.gl_pathv;
puts("MATCHES");
for(;*a;a++)
puts(*a);
}
globfree(&globbuf);
}
Running: 正在运行:
./a.out 'lockfile*'
should give you your lockfiles. 应该给你你的锁文件。
To my knowledge, that's how it should be done. 据我所知,这就是应该做的事情。
For each name d_name
of the file, you can check it's length and if it has at least 8 characters, strcmp
that 8 first characters to lockfile . 对于文件的每个名称
d_name
,您都可以检查文件的长度,并且如果文件名至少包含8个字符,请将strcmp
前8个字符strcmp
到lockfile 。
You can also use <regex.h>
for that check. 您也可以使用
<regex.h>
进行检查。
As for the iteration, I believe that's he best way to go. 至于迭代,我相信这是他最好的方法。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.