Linux获取目录下的所有文件

本文介绍了一个使用C++在Linux环境下遍历指定目录及其子目录下所有文件的方法。通过使用dirent.h库,代码实现了获取目录下的普通文件和递归处理子目录的功能。此程序为理解和实现Linux文件系统操作提供了实例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Linux获取目录下的所有文件

#include <sys/types.h>
#include <sys/stat.h>
#include <dirent.h>
#include <cstddef>
#include <string>
#include <iostream>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <vector>
using namespace std;
void getFiles(std::string path, std::vector<std::string> &files)
{
  DIR *dir;
  struct dirent *ptr;

  if ((dir = opendir(path.c_str())) == NULL)
  {
    perror("Open dir error...");
    exit(1);
  }

  while ((ptr = readdir(dir)) != NULL)
  {
    if (strcmp(ptr->d_name, ".") == 0 || strcmp(ptr->d_name, "..") == 0)
      continue;
    else if (ptr->d_type == 8) // 普通文件
      files.push_back(path + ptr->d_name);
    else if (ptr->d_type == 10) // 符号链接
      continue;
    else if (ptr->d_type == 4) // 目录文件
    {
      //files.push_back(ptr->d_name);
      getFiles(path + ptr->d_name + "/", files);
    }
  }
  closedir(dir);
}

int main()
{
  vector<string> strVec;
  getFiles("/home/xxx/", strVec);
  for (int i = 0; i < strVec.size(); i++)
  {
    cout << strVec[i] << endl;
  }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值