Linux下查看一个文件的类型

来源:互联网 发布:电脑无法连接有线网络 编辑:程序博客网 时间:2024/06/09 07:38

Linux操作系统中,文件类型分为七类:

1、普通文件

2、目录(文件夹)

3、面向块的设备文件(磁盘、磁带)

4、面向字符的设备文件(纸带输入/穿孔输入机、打印机)

5、符号链接

6、管道pipe及命名管道FIFO

7、套接字


下面是使用stat系统调用函数来判断文件类型的自定义函数:

#include<sys/types.h>#include<sys/stat.h>#include<unistd.h>#include<stdio.h> void file_type(char* path){    struct stat stat_buf;    int res=stat(path,&stat_buf);    if(res==0)    {        if(S_ISREG(stat_buf.st_mode))            printf("%s is regular file\n",path);        else if(S_ISDIR(stat_buf.st_mode))            printf("%s is directory\n",path);        else if(S_ISCHR(stat_buf.st_mode))            printf("%s is character device\n",path);        else if(S_ISBLK(stat_buf.st_mode))            printf("%s is block device\n",path);        else if(S_ISSOCK(stat_buf.st_mode))            printf("%s is socket\n",path);        else if(S_ISLNK(stat_buf.st_mode))            printf("%s is soft link\n",path);        else if(S_ISFIFO(stat_buf.st_mode))            printf("%s is FIFO\n",path);    }    else        printf("path error\n"); } int main(int* argc,char* argv[]){    char path[50];    printf("Please input the file path:\n");    while(scanf("%s",path)!=EOF)        file_type(path);    return 0;}

以上代码中,通过以st_mode作为参数来检查文件类型的宏包括:

S_ISREG(m)  is it a regular file?S_ISDIR(m)  directory?S_ISCHR(m)  character device?S_ISBLK(m)  block device?S_ISFIFO(m) FIFO (named pipe)?S_ISLNK(m)  symbolic link? (Not in POSIX.1-1996.)S_ISSOCK(m) socket? (Not in POSIX.1-1996.)

其中,参数m代表st_mode。 

原创粉丝点击