#navi(contents-page-name): No such page: ファイル

ディレクトリかどうか判別する・stat

指定したパスがディレクトリかどうかを判別するC言語サンプルコードを以下に記します。

c-top.html is not found or not readable.

関連記事

statを使用したC言語サンプルコード

&ref(): File not found: "isdir.c" at page "ファイル/ディレクトリかどうか判別する・stat"; (改行コード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言語サンプルコードでした。

c-btm.html is not found or not readable.

トップ   新規 一覧 検索 最終更新   ヘルプ   最終更新のRSS