#navi(../)
* ディレクトリかどうか判別する・stat [#oc9fcf36]
指定したパスがディレクトリかどうかを判別するC言語サンプルコードを以下に記します。

#contents
#htmlinsertpcsp(c-top.html,c-sp.html)

* 関連記事 [#ufe2733c]
-[[テキストファイルを行単位で読み込む・fgets>ファイル/テキストファイルを行単位で読み込む・fgets]]
-[[ディレクトリかどうか判別する・stat>ファイル/ディレクトリかどうか判別する・stat]]
-[[指定したディレクトリのファイル一覧を取得する・opendir,readdir>ファイル/指定したディレクトリのファイル一覧を取得する・opendir,readdir]]
-[[ファイルのサイズを取得する>ファイル/ファイルのサイズを取得する・stat]]
-[[ファイルのユーザIDとグループIDを取得する>ファイル/ファイルのUIDとGIDを取得する・stat]]
-[[fopenのファイルモード一覧表>ファイル/fopenのファイルモード一覧表]]
-[[バイナリファイルの書き込みと読み込み・fopen,fwrite,fread>ファイル/バイナリファイルの書き込みと読み込み・fopen,fwrite,fread]]

* statを使用したC言語サンプルコード [#e6b48ef9]
&ref(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言語サンプルコードでした。

#htmlinsertpcsp(c-btm.html,c-sp.html)

トップ   編集 差分 バックアップ 添付 複製 名前変更 リロード   新規 一覧 検索 最終更新   ヘルプ   最終更新のRSS