指定したパスがディレクトリかどうかを判別するC言語サンプルコードを以下に記します。
isdir.c (改行コードLF)
#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
void usage(char *cmd)
{
fprintf(stderr, "Usage: %s <path>\n", cmd);
}
int main(int argc, char *argv[])
{
struct stat st;
int result;
if (argc != 2) {
usage(argv[0]);
return 1;
}
result = stat(argv[1], &st);
if (result != 0) {
fprintf(stderr, "%s is not found.\n", argv[1]);
return 1;
}
if ((st.st_mode & S_IFMT) == S_IFDIR) {
printf("%s is directory.\n", argv[1]);
}
else {
printf("%s is not directory.\n", argv[1]);
}
return 0;
}
stat関数を用いてディレクトリかどうかを確認しています。
上記のC言語サンプルコードを参考にして見てください。
以下にコンパイルし実行した時の結果を記します。
$ gcc isdir.c -o isdir
$ ./isdir /etc /etc is directory.
$ ./isdir /etc/hosts /etc/hosts is not directory.
以上、stat関数を使用してディレクトリかどうかを確認するC言語サンプルコードでした。