<<戻る

2004年10月07日

ファイル情報とディレクトリ情報の取得

 

ファイル情報の取得

#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <time.h>

/*
 * stat,fstatはPOSIX準拠
 */
int main(int argc, char *argv[])
{
	struct stat meta;

	/* ファイル情報の取得 */
	if ( stat(__FILE__, &meta) != 0 )
	{
		perror("can not get status.\n");
		return 0;
	}

	/* 情報の表示 */
	printf("name  :%s\n",				__FILE__);
	printf("device:%d\n",		(int) meta.st_dev);
	printf("inode :%d\n",		(int) meta.st_ino);
	printf("mode  :%o\n",		(int) meta.st_mode); /* octet */
	printf("mode  :%x\n",		(int) meta.st_mode); /* hex */
	printf("nlink :%d\n",		(int) meta.st_nlink);/* hardlink */
	printf("uid   :%d\n",		(int) meta.st_uid);
	printf("gid   :%d\n",		(int) meta.st_gid);
	printf("rdev  :%d\n",		(int) meta.st_rdev); 
	printf("size  :%d\n", 		(int) meta.st_size);
	printf("blksiz:%d\n",		(int) meta.st_blksize);
	printf("blks  :%d\n",		(int) meta.st_blocks);
	printf("atime :%s",			ctime(&meta.st_atime));		/* last access */	
	printf("mtime :%s",			ctime(&meta.st_mtime));		/* last modify */
	printf("ctime :%s",			ctime(&meta.st_ctime));		/* last change */
	

	/* モード */
	/* 0000 0000 0000 0000
	 *         |         | permission
	 *      | |            suid, sgid sticky,
	 * |  |                file mode
	 */
	switch ( meta.st_mode & S_IFMT ) /* S_IFMT 0xF000 */
	{
		case S_IFREG:
			printf("REGuler file\n");
			break;
		case S_IFDIR:
			printf("DIRectory\n");
			break;
		case S_IFIFO:
			printf("fifo\n");
			break;
		case S_IFCHR:
			printf("character device\n");
			break;
		case S_IFBLK:
			printf("block device\n");
			break;
		case S_IFLNK:
			printf("symobolic link\n");
			break;
		case S_IFSOCK:
			printf("socket\n");
			break;
	}
	return 0;
}
 

 

ディレクトリ情報の取得

#include <sys/types.h>
#include <dirent.h>
#include <stdio.h>
#include <stdlib.h>

/* ディレクトリ情報を取得する */
int main(int argc, char *argv[])
{
	DIR *dir;
	struct dirent *meta;

	dir = opendir(".");
	if ( dir == NULL )
	{
		perror("dir open error\n");
		exit(1);
	}

	meta = (struct dirent *) malloc(sizeof(struct dirent));
	free(meta);
	while ( (meta = readdir(dir)) != NULL ) {
		/* ディレクトリ情報の表示 */
		printf("inode   :%d\n", (int) meta->d_ino);
		printf("d_off   :%d\n", (int) meta->d_off);
		printf("d_reclen:%d\n",       meta->d_reclen);
		printf("d_name  :%s\n",       meta->d_name);
	}


	if ( closedir(dir) == -1 )
	{
		perror("dir close error\n");
		exit(1);
	}

	return 0;
}