In C, checking for existence of file with name matching a pattern

心已入冬 提交于 2019-12-19 11:26:29

问题


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. 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. 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. It works, but I sure would like a more compact way to do this. Any ideas?


回答1:


You can use glob(3) (standardized by 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.




回答2:


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.

You can also use <regex.h> for that check.

As for the iteration, I believe that's he best way to go.



来源:https://stackoverflow.com/questions/42680439/in-c-checking-for-existence-of-file-with-name-matching-a-pattern

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!