美文网首页
linux中c++读取目录和子目录下文件

linux中c++读取目录和子目录下文件

作者: Then丶 | 来源:发表于2020-06-08 07:48 被阅读0次
#include <sys/types.h>
#include <sys/stat.h>
#include <iostream>
#include <unistd.h>
#include <dirent.h>
#include <cstddef>
#include <string>
#include <vector>
#include <cstring>

void getFiles(std::string path, std::vector<std::string> &files);

int main(int argc, char **argv)
{
    using namespace std;

    string path = "/root/git/Cplusplus/test/";
    vector<string> vec;

    getFiles(path, vec);

    for(auto &s : vec)
        cout << s << endl;

}

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);
  }

  /*
   * 文件(8)、目录(4)、链接文件(10)
   */

  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);
}

#include <stdio.h>
#include <cstring>
#include <fcntl.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <dirent.h>
#include <errno.h>

//搜索 指定目录下的所有文件及其子目录下的文件
void getFileName(char * dirPath)
{
  DIR *dir=opendir(dirPath);

  if(dir==NULL)
  {
  printf("%s\n",strerror(errno));
  return;
  }
  chdir(dirPath);//进入到当前读取目录
  struct dirent *ent;
  while((ent=readdir(dir)) != NULL)
  {
  if(strcmp(ent->d_name,".")==0||strcmp(ent->d_name,"..")==0)
  {
   continue;
  }
  int size = strlen(ent->d_name); 
  if(strcmp( ( ent->d_name + (size - 4) ) , ".cpp") != 0)  //只存取.gmm 扩展名的文件名 
   continue;
   
  struct stat st;
  stat(ent->d_name,&st);
  if(S_ISDIR(st.st_mode))  //如果是子目录,继续递归搜索
  {
   getFileName(ent->d_name);
  }
  else
  {
   printf("%s\n",ent->d_name);
  }
  }
  closedir(dir);
  chdir("..");//返回当前目录的上一级目录
}

int main(int argc, char *argv[])

{

  getFileName("/root/git/Cplusplus/test/"); 

  return 0;

}

https://blog.csdn.net/lei19880402/article/details/105774663
https://blog.csdn.net/yang_qi168/article/details/21723205

相关文章

网友评论

      本文标题:linux中c++读取目录和子目录下文件

      本文链接:https://www.haomeiwen.com/subject/seiktktx.html