8
9

More than 5 years have passed since last update.

C言語でglob

Posted at

globというライブラリがあり、これはpatternでしていしたパスを全部とってくることが可能です。

下記は、現在のフォルダにあるxxx.txtというファイルのパスをすべて取得するものです。

globtest.c
#include <stdio.h>
#include <glob.h>

int main(void)
{
    glob_t globbuf;
    int i;

    int ret = glob("./*.txt", 0, NULL, &globbuf);
    for (i = 0; i < globbuf.gl_pathc; i++) {
        printf("%s\n", globbuf.gl_pathv[i]);
    }
    globfree(&globbuf);

    return 0;
}

これは、第1引数で指定したパターンのパスをすべてglobbuf.gl_pathvに格納されています。
ヒットしたパスの数は、globbuf.gl_pathcに入っています。

ただ、globが使えない環境もあります(Androidのndkとか)
その場合は、opendir/readdirとか、strxxx等を駆使して頑張らないといけないです。
下記は、上記をglobを使わないで書きなおしたものです。

dirtest.c
#include <sys/types.h>
#include <stdio.h>
#include <dirent.h>
#include <string.h>
#include <malloc.h>

int main(void)
{

    DIR *dir = opendir(".");
    struct dirent *dp;
    while ((dp = readdir(dir)) != NULL) {
        char *p = strchr(dp->d_name, 0);
        if (strstr(p-sizeof(".txt"), ".txt")) {
            char *s = malloc(2 + sizeof(dp->d_name) + 1);
            strncpy(s, "./\0", 3);
            s = strcat(s, dp->d_name);
            printf("%s\n", s);
            free(s);
        }
    }
    close(dir);
}
8
9
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
8
9