当前位置: 首页 > news >正文

Linux目录遍历函数

1.打开一个目录

#include <sys/types.h>

#include <dirent.h>

    DIR *opendir(const char *name);

    参数:

        -name:需要打开的目录的名称

    返回值:

        DIR * 类型,理解为目录流

        错误返回NULL

2.读取目录中的数据

#include <dirent.h>

    struct dirent *readdir(DIR *dirp);

    参数

        -dirp是opendir返回的结果

    返回值:

        struct dirent,代表读取到的文件的信息

        读取到了末尾或者失败了返回NULL

3.关闭目录

#include <sys/types.h>

#include <dirent.h>

       int closedir(DIR *dirp);

#include <sys/types.h>
#include <dirent.h>
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
#include <errno.h>
int getFileNum(const char* path);
int main(int argc, char * argv[]) {if(argc < 2) {printf("%s path\n", argv[0]);return -1;}int num = getFileNum(argv[1]);printf("普通文件的个数为:%d\n", num);return 0;
}
//用于获取目录下所有普通文件的个数
int getFileNum(const char* path) {//打开目录DIR * dir = opendir(path);if(dir == NULL) {perror("opendir");exit(0);}struct dirent* ptr;//定义变量,记录普通文件的个数int total = 0;while((ptr = readdir(dir)) != NULL) {//获取名称char * dname = ptr->d_name;//忽略掉.和..if(strcmp(dname, ".") == 0 || strcmp(dname, "..") == 0) {continue;}//判断是普通文件还是目录if(ptr->d_type == DT_DIR) {//目录,需要继续读取这个目录char newpath[256];sprintf(newpath, "%s/%s", path, dname);total += getFileNum(newpath);}if(ptr->d_type == DT_REG) {//普通文件total++;}}//关闭目录closedir(dir);return total;
}

http://www.lryc.cn/news/166097.html

相关文章:

  • 数据库-理论基础
  • 【已解决】src/spt_python.h:14:20: 致命错误:Python.h:没有那个文件或目录
  • 基于Face++网络爬虫+人脸融合算法智能发型推荐程序——深度学习算法应用(含Python及打包exe工程源码)+爬虫数据集
  • Jetson nano嵌入式平台配置ip记录
  • 前端中的跨域请求及其解决方案
  • SpringBoot2.0(mybatis-plus初始使用)
  • 游戏视频录制软件对比,哪款最适合你的需求?
  • 耐蚀合金连续油管最新版 学习记录
  • LoGoNet:基于局部到全局跨模态融合的精确 3D 目标检测
  • Python 多线程、线程池、进程池
  • 深入浅出了解华为端到端交付流程的概念和5个关键点
  • [Linux]进程信号
  • PostgreSQL 数据类型
  • 智慧港口4G+UWB+GPS/北斗RTK人员定位系统解决方案
  • 实时时钟和日历电路芯片MS85163/MS85163M
  • 【Java从入门到精通】这也许就是Java火热的原因吧!
  • zTasker—简洁易用强大的定时热键一体自动化工具,效率倍增器
  • 惊艳时装界!AIGC风暴来袭,从设计到生产的全新体验
  • element -ui table表格内容无限滚动 使用插件vue-seamless-scroll
  • 如何在windows环境下编译T
  • USB接口针式打印机
  • 外贸建站教程步骤有哪些?独立站怎么搭建?
  • useGetState自定义hooks解决useState 异步回调获取不到最新值
  • input子系统框架、外设驱动开发
  • Google Chrome 浏览器以全屏模式打开
  • 安装torch113、cuda116并运行demo【Transformer】
  • 基于scRNA-seq的GRN分析三阴性乳腺癌的肿瘤异质性
  • Python:二进制文件实现等间隔取相同数据量并合并
  • python使用openvc库进行图像数据增强
  • 如何利用Api接口获取手机当前的网络位置信息