文件类型在Unix上的分类与判断

Unix/Linux 上的文件类型分为以下几类:

序号 分类名称 英文名称 文件类型判断宏 说明
1 普通文件 regular file S_ISREG() 最常见的文件类型
2 目录文件 directory file S_ISDIR() 目录
3 块特殊文件 block special file S_ISBLK() 提供对设备(如磁盘)带缓冲的访问,每次访问以固定长度为单位进行
4 字符特殊文件 character special file S_ISCHR() 提供对设备不带缓冲的访问,每次访问长度可变
5 命名管道 FIFO or named pipe S_ISFIFO() 用于进程间通信
6 套接字 socket S_ISOCK() 用于网络通信
7 符号链接 symbolic link S_ISLNK() 软链接/硬链接

具体判断文件类型的代码如下所示(取自《UNIX环境高级编程》示例代码):

#include "apue.h"
//#include <sys/stat.h>

int
main(int argc, char *argv[])
{
	int			i;
	struct stat	buf;
	char		*ptr;

	for (i = 1; i < argc; i++) {
		printf("%s: ", argv[i]);
		if (lstat(argv[i], &buf) < 0) {
			err_ret("lstat error");
			continue;
		}
		if (S_ISREG(buf.st_mode))
			ptr = "regular";
		else if (S_ISDIR(buf.st_mode))
			ptr = "directory";
		else if (S_ISCHR(buf.st_mode))
			ptr = "character special";
		else if (S_ISBLK(buf.st_mode))
			ptr = "block special";
		else if (S_ISFIFO(buf.st_mode))
			ptr = "fifo";
		else if (S_ISLNK(buf.st_mode))
			ptr = "symbolic link";
		else if (S_ISSOCK(buf.st_mode))
			ptr = "socket";
		else
			ptr = "** unknown mode **";
		printf("%sn", ptr);
	}
	exit(0);
}

 

Advertisements

发表评论

Fill in your details below or click an icon to log in:

WordPress.com 徽标

You are commenting using your WordPress.com account. Log Out /  更改 )

Google+ photo

You are commenting using your Google+ account. Log Out /  更改 )

Twitter picture

You are commenting using your Twitter account. Log Out /  更改 )

Facebook photo

You are commenting using your Facebook account. Log Out /  更改 )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.