0

我正在尝试递归获取目录的所有文件和子文件夹。这是我到目前为止所拥有的。

#include <iostream>
#include "dirent.h"
#include <io.h>

using namespace std;

void listDir(char *directory)
{
    DIR *dir;
    struct dirent *ent;
    if((dir = opendir (directory)) != NULL)
    {
        while ((ent = readdir (dir)) != NULL)
        {
            if(strstr(ent->d_name,".") != NULL)
                cout<<ent->d_name<<endl;
            else
            {
                strcat(directory,ent->d_name);
                strcat(directory,"\\");
                strcat(directory,"\0");
                cout<<directory<<endl;
                cin.get();
                listDir(directory);
            }
        }
    }
    closedir (dir);
}

int main(int param, char **args)
{
    char *path = new char[];
    path = args[1];
    strcat(path, "\\");
    listDir(path);
    cin.get();
    return 0;
}

我正在使用 dirent (实际上很酷,如果您还没有的话,请获取它)并且当我递归获取文件夹时,它似乎添加到我的子文件夹末尾的目录中。例如:

下载、图像和包含都是我的 Jakes625 文件夹的子文件夹。也许我错过了什么?

4

2 回答 2

0
#include <unistd.h>
#include <dirent.h>

#include <iostream>

using namespace std;

void listDir(const string& path)
{
  DIR *dir;
  struct dirent *ent;

  if((dir = opendir (path.c_str())) != NULL)
  {
    while ((ent = readdir (dir)) != NULL)
    {
      if(string(ent->d_name).compare(".") != 0)
      {
        cout<< ent->d_name << endl;
      }
      else
      {
        string nextDir = string(ent -> d_name);
        nextDir += "\\";

        cout <<  nextDir << endl;

        listDir(nextDir);
      }
    }
  }

  closedir (dir);
}

int main(int param, char **args)
{
  string path = string(args[1]);
  listDir(path);

  return 0;
}

I rewrote it so that it uses c++ strings: there's no reason to use C strings here. It works now. There were a number of minor problems, but the most significant was that you didn't specify a size when you went to allocate a char array. This line was the culprit:

char *path = new char[]; // bad!

If you don't specify a size then the allocator doesn't know how many bytes to request from the heap. Your program didn't require heap allocation because there was no case where data needed to outlive its enclosing lexical block.

于 2013-04-01T22:13:35.900 回答
0

https://en.cppreference.com/w/cpp/filesystem/recursive_directory_iterator

    for(auto& p: fs::recursive_directory_iterator("my_directory"))
        std::cout << p.path() << '\n';

这是一个例子

#include <fstream>
#include <iostream>
#include <filesystem>
namespace fs = std::filesystem;
 
int main()
{
    fs::current_path(fs::temp_directory_path());
    fs::create_directories("sandbox/a/b");
    std::ofstream("sandbox/file1.txt");
    fs::create_symlink("a", "sandbox/syma");
    for(auto& p: fs::recursive_directory_iterator("sandbox"))
        std::cout << p.path() << '\n';
    fs::remove_all("sandbox");
}

输出:

"sandbox/a"
"sandbox/a/b"
"sandbox/file1.txt"
"sandbox/syma"
于 2021-04-07T22:15:12.410 回答