Linux C判断文件是否为目录或者是普通文件

    xiaoxiao2021-03-26  26

    主要函数: stat(),opendir(),readdir(),

    主要结构体:struct dirent  和 struct stat

    主要宏:S_ISDIR(),     S_ISREG()

    函数 stat()用于获取一个文件路径的信息,并把获取到的信息放到结构体 struct stat 中

    函数 opendir()用于生成一个目录指针DIR

    函数readdir()用于读取目录指针 DIR 中的信息,返回的值为一个 struct dirent 结构体

    结构体struct dirent 用于保存一个目录的属性。这里用到的只是该结构体的 d_name 成员,用于保存目录下的文件名

    结构体 struct stat 用于保存 一个文件路径的信息

    宏S_ISDIR()用于判断一个文件路径是不是一个目录,是则返回1,否则返回0

    宏S_ISREG()用于判断一个文件路径是不是一个普通文件,是则返回1,否则返回0

    下面给出代码:

    #include <stdio.h> #include <dirent.h> #include <stdlib.h> #include <string.h> #include <sys/types.h> #include <sys/stat.h> int main(int argc, char const *argv[]) { char const*path = argv[1]; struct stat s_buf; /*获取文件信息,把信息放到s_buf中*/ stat(path,&s_buf); /*判断输入的文件路径是否目录,若是目录,则往下执行,分析目录下的文件*/ if(S_ISDIR(s_buf.st_mode)) { printf("[%s] it is a dir\n",path); struct dirent *filename; DIR *dp = opendir(path); /*readdir()必须循环调用,要读完整个目录的文件,readdir才会返回NULL 若未读完,就让他循环*/ while(filename = readdir(dp)) { /*判断一个文件是目录还是一个普通文件*/ char file_path[200]; bzero(file_path,200); strcat(file_path,path); strcat(file_path,"/"); strcat(file_path,filename->d_name); /*获取文件信息,把信息放到s_buf中*/ stat(file_path,&s_buf); /*判断是否目录*/ if(S_ISDIR(s_buf.st_mode)) { printf("[%s] is a dir\n",file_path); } /*判断是否为普通文件*/ if(S_ISREG(s_buf.st_mode)) { printf("[%s] is a regular file\n",file_path); } } } /*若输入的文件路径是普通文件,则打印并退出程序*/ else if(S_ISREG(s_buf.st_mode)) { printf("[%s] is a regular file\n",path); return 0; } return 0; }

    转载请注明原文地址: https://ju.6miu.com/read-659579.html

    最新回复(0)