Linux系统编程 --- 如何列出一个目录下面的所有文件

      linux平台可以使用opendir函数来打开一个目录,用readdir读取目录当中的一个entry(一个entry可以是子目录,文件,软硬链接等),如果需要读取所有目录下面的文件,需要使用while((entry = readdir(dp))) 来读去每个entry,直到读取的entry == NULL。

      还有需要注意的就是目录打开之后,需要自己关闭的,可以调用closedir(DIR*)来关闭,这个和文件fd的操作非常类似,不会的同学可以参考标准的stdio文件操作。

      下面代码是从wiki上面摘过来的, listdir扮演了打印指定目录下面所有文件的功能,类似于linux命令"ls"的功能。

/**************************************************************
* A simpler and shorter implementation of ls(1)
* ls(1) is very similar to the DIR command on DOS and Windows.
**************************************************************/
#include <stdio.h>
#include <dirent.h>

int listdir(const char *path) {
  struct dirent *entry;
  DIR *dp;

  dp = opendir(path);
  if (dp == NULL) {
    perror("opendir");
    return -1;
  }

  while((entry = readdir(dp)))
    puts(entry->d_name);

  closedir(dp);
  return 0;
}

int main(int argc, char **argv) {
  int counter = 1;

  if (argc == 1)
    listdir(".");

  while (++counter <= argc) {
    printf("\nListing %s...\n", argv[counter-1]);
    listdir(argv[counter-1]);
  }

  return 0;
}

转载于:https://my.oschina.net/meegozu/blog/12702

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值