目次から探す
ファイル名のフィルタリングとソート
ファイル名を取得するだけでなく、特定の条件に基づいてファイルをフィルタリングしたり、ソートしたりすることもできます。
ここでは、拡張子によるフィルタリング、ファイル名の一部によるフィルタリング、そしてファイル名のソートについて説明します。
拡張子によるフィルタリング
特定の拡張子を持つファイルのみを取得したい場合、以下のような方法でフィルタリングすることができます。
#include <stdio.h>
#include <dirent.h>
#include <string.h>
int main() {
DIR *dir;
struct dirent *entry;
dir = opendir(".");
if (dir == NULL) {
perror("opendir");
return 1;
}
while ((entry = readdir(dir)) != NULL) {
// ファイル名の拡張子を取得
char *ext = strrchr(entry->d_name, '.');
if (ext != NULL && strcmp(ext, ".txt") == 0) {
printf("%s\n", entry->d_name);
}
}
closedir(dir);
return 0;
}
上記の例では、カレントディレクトリ内のファイルの中から拡張子が .txt
のファイルのみを表示しています。
readdir 関数
で取得したファイル名の中から、strrchr 関数
を使って拡張子を取得し、strcmp 関数
で .txt
と比較しています。
一致する場合にはそのファイル名を表示します。
ファイル名の一部によるフィルタリング
ファイル名の一部に基づいてフィルタリングする場合も、同様の方法で行うことができます。
以下の例では、ファイル名に test
という文字列が含まれているファイルのみを表示しています。
#include <stdio.h>
#include <dirent.h>
#include <string.h>
int main() {
DIR *dir;
struct dirent *entry;
dir = opendir(".");
if (dir == NULL) {
perror("opendir");
return 1;
}
while ((entry = readdir(dir)) != NULL) {
if (strstr(entry->d_name, "test") != NULL) {
printf("%s\n", entry->d_name);
}
}
closedir(dir);
return 0;
}
ファイル名のソート
ファイル名をソートするには、取得したファイル名を配列に格納し、ソート関数を使って並び替える方法があります。
以下の例では、ファイル名を昇順にソートして表示しています。
#include <stdio.h>
#include <dirent.h>
#include <string.h>
#include <stdlib.h>
int compare(const void *a, const void *b) {
return strcmp(*(const char **)a, *(const char **)b);
}
int main() {
DIR *dir;
struct dirent *entry;
int count = 0;
dir = opendir(".");
if (dir == NULL) {
perror("opendir");
return 1;
}
while ((entry = readdir(dir)) != NULL) {
count++;
}
rewinddir(dir);
char **filenames = (char **)malloc(count * sizeof(char *));
int i = 0;
while ((entry = readdir(dir)) != NULL) {
filenames[i] = strdup(entry->d_name);
i++;
}
qsort(filenames, count, sizeof(char *), compare);
for (i = 0; i < count; i++) {
printf("%s\n", filenames[i]);
free(filenames[i]);
}
free(filenames);
closedir(dir);
return 0;
}
上記の例では、ファイル名を格納するためのポインタの配列 filenames
を動的に確保し、readdir 関数
で取得したファイル名を strdup 関数
を使ってコピーしています。
その後、qsort 関数
を使って配列をソートし、ソートされたファイル名を表示しています。
これらの方法を使うことで、より効率的にファイルを取得することができます。