Linux Advance--打印文件类型

来源:互联网 发布:windows字体有哪些 编辑:程序博客网 时间:2024/04/29 08:24

文件相关的信息存放在结构体 stat 中:

struct stat {mode_tst_mode;/* file type & mode (permissions) */ino_tst_ino;/* i-node number (serial number) */dev_tst_dev;/* device number (file system) */dev_tst_rdev;/* device number for special file */nlink_tst_nlink;/* number of links */uid_tst_uid;/* user ID of owner */gid_tst_gid;/* group ID of owner */off_tst_size;/* size in bytes, for regular files */time_tst_atime;/* time of last access */time_tst_mtime;/* time of last modification */time_tst_ctime;/* time of last file status change */blksize_tst_blksize;/* best I/O block size */blkcnt_tst_blocks;/* number of disk blocks allocated */};

与此相关的函数声明如下:

#include <sys/stat.h>int stat(const char *restrict pathname, struct stat *restrict buf);int fstat(int filedes, struct stat *buf);int lstat(const char *restrict pathname, struct stat *restrict buf);

下面介绍Linux的基本文件类型:

1、普通文件 (regular file)

2、目录文件 (directory file)

3、块特殊文件 (block special file):这种文件类型提供对设备带缓冲的访问,每次访问以固定长度为单位进行。

4、字符特殊文件 (character special file):这种文件类型提供对设备不带缓冲的访问,每次访问长度可变。系统中的所有设备要么是字符特殊文件,要么是块特殊文件。

5、FIFO:这种类型作用于进程间通信,有时也将其称为命名管道(named pipe)。

6、套接字 (socket):这种文件类型作用于进程间的网络通信。

7、符号链接 (symbolic link):这种文件类型指向另一个文件。


文件类型包含在 stat 结构的 st_mode 成员中,下面是文件类型宏:

S_ISREG()普通文件S_ISDIR()目录文件S_ISCHR()字符特殊文件S_ISBLK()块特殊文件S_ISFIFO()管道或FIFOS_ISLNK()符号链接S_ISSOCK()套接字


这里我们用 lstat 读取文件的信息,更多关于 stat 的信息可以点此查看,下面是代码:

#include <stdio.h>#include <sys/stat.h>int main(int argc, char *argv[]){    inti;    struct stat buf;    char *ptr;    for (i=1; i<argc; i++) {printf("%s: ", argv[i]);if (lstat(argv[i], &buf) < 0) {printf("lstat error\n");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";elseptr = "** unknown mode **";printf("%s\n", ptr);    }exit(0);}

实验结果如下:



1 0
原创粉丝点击