Linux下查看一个文件的类型

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。 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值