関数stat
を使えばいい。関数stat
1.
2.
#include <sys/stat.h>
int stat(const char *pathname, struct stat *sbuf)
stat構造体
はsys/stat.h
内で定義されている。stat構造体
のメンバの型はsys/types.h
内で
typedef
されている。stat構造体メンバの一部
1.
2.
3.
4.
5.
6.
7.
8.
9.
struct stat
{
/*stat構造体メンバの一部*/
mode_t st_mode; // short ファイルモード
off_t st_size; // long ファイルのサイズ
_TIME_T st_atime; // time_t 最後にアクセスされた時刻
_TIME_T st_mtime; // time_t 最後に修正された時刻
_TIME_T st_ctime; // time_t 最後に属性変更された時刻
};
st_mode
をS_IFMT
でマスクすることで、それがファイルなのかディレクトリなのかを判断することができる。ファイルとディレクトリとで処理を分岐する例
1.
2.
3.
4.
5.
6.
7.
8.
9.
switch( s.st_mode & S_IFMT )
{
case S_IFREG:
ファイルの時の処理;
break;
case S_IFDIR:
ディレクトリの時の処理;
break;
}
ディレクトリ・ファイル判定用のマクロ
1.
2.
#define S_ISDIR(mode) ((mode&S_IFMT) == S_IFDIR)
#define S_ISREG(mode) ((mode&S_IFMT) == S_IFREG)
サンプル
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
17.
18.
19.
20.
21.
22.
23.
24.
25.
26.
27.
28.
29.
30.
31.
32.
33.
34.
35.
36.
37.
38.
39.
40.
41.
42.
43.
44.
45.
46.
47.
48.
49.
50.
51.
52.
53.
54.
55.
56.
#include <stdio.h>
#include <time.h>
#include <sys/stat.h>
int main(int argc,char *argv[])
{
int i;
if(argc == 1)
{
printf("don't file inputed\n");
return 0;
}
for(i=1; i<argc; i++)
{
struct stat fileStat;
time_t t;
// 入力ファイルの情報を取得
if( stat(argv[i],&fileStat) != 0 )
perror("argv[i]");
// ファイルのモード
switch( fileStat.st_mode & S_IFMT )
{
case S_IFREG: // ファイル
printf("this is file\n");
break;
case S_IFDIR: // ディレクトリ
printf("this is directry\n");
break;
}
// ファイルのサイズ
printf("file size : %d\n",fileStat.st_size);
// 最後にアクセスされた時刻
t = fileStat.st_atime;
printf("acsess time\t\t: %s",ctime(&t));
// 最後に修正された時刻
t = fileStat.st_mtime;
printf("modification time\t: %s",ctime(&t));
// 最後に属性変更された時刻
t = fileStat.st_ctime;
printf("status change time\t: %s",ctime(&t));
}
{
char c;
c = getchar();
}
return 0;
}
0 件のコメント:
コメントを投稿