Linux C判断文件是否为目录或者是普通文件
来源:互联网 发布:动力节点java项目 编辑:程序博客网 时间:2024/05/17 02:54
主要函数: 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;}
0 0
- Linux C判断文件是否为目录或者是普通文件
- C++——判断文件或者目录是否存在
- linux shell判断文件,目录是否存在或者具有权限
- [IO]判断文件或者目录是否存在
- shell判断目录或者文件是否存在
- 判断文件是否是目录文件
- 判断是否为文件夹或者文件
- VC判断是否为文件夹或者文件
- c#---判断文件或者文件夹是否存在
- shell 判断文件/目录是否为空
- vc 判断是否为文件或目录
- shell 判断文件/目录是否为空
- linux c目录与普通文件
- linux+笔记:linux下判断一个文件或者目录是否存在
- Linux C 库函数判断一个文件是否为空
- shell判断文件,目录是否存在或者具有权限
- shell判断文件,目录是否存在或者具有权限
- shell判断文件,目录是否存在或者具有权限
- JavaServer Faces 2.2 can not be installed
- HDU5898 odd-even number(数位dp)
- javascript模块化之CommonJS、AMD、CMD、UMD、ES6
- 新的一年
- 【Mrpc】 Demo1 对象与byte[]的相互转换
- Linux C判断文件是否为目录或者是普通文件
- iOS开发 多个cell在初始化时注意重用池
- 如何搭建一个完整的视频直播运营平台,需要的投入多大?
- 二叉树的几种遍历方法
- overridePendingTransition的使用与调用相机拍照
- keras 对于大数据的训练,无法一次性载入内存,使用迭代器
- Android 官方示例:android-architecture 学习笔记(二)之todo-mvp
- Spiral Matrix
- iOS开发 利用cell上的view获得这个cell以及他的indexpath和row