侧边栏壁纸
  • 累计撰写 185 篇文章
  • 累计创建 77 个标签
  • 累计收到 17 条评论

目 录CONTENT

文章目录

Linux中C语言如何获取指定目录中的所有文件和文件夹

码峰
2022-11-03 / 0 评论 / 0 点赞 / 792 阅读 / 198 字 / 正在检测是否收录...
广告 广告

需求描述

在Linux中使用C语言开发时,有时候需要获取指定目录中的文件和文件夹,当然,可以使用“exec"执行"ls"命令,取得命令的输出结果来获取,但解析结果还是挺麻烦了,使用POSIX的兼容的API dirent.h中的函数来获取就可以了。

示例代码

以下是在linux中使用POSIX兼容的API,opendir、readdir获取指定目录中的所有文件和文件夹的示例代码。

/*
 * This program displays the names of all files in the current directory.
 */

#include <dirent.h> 
#include <stdio.h> 

int main(void) {
  DIR *d;
  struct dirent *dir;
  d = opendir(".");
  if (d) {
    while ((dir = readdir(d)) != NULL) {
      printf("%s\n", dir->d_name);
    }
    closedir(d);
  }
  return(0);
}
0
广告 广告

评论区