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

后端 未结 2 1670
南旧
南旧 2021-01-07 09:30

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

相关标签:
2条回答
  • 2021-01-07 09:54

    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.

    0 讨论(0)
  • 2021-01-07 10:06

    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.

    0 讨论(0)
提交回复
热议问题