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を使用しています(実際にはかなりクールです。まだ取得していない場合は取得してください)。フォルダーを再帰的に取得すると、サブフォルダーの最後のディレクトリに追加されるようです。例えば:

Downloads、Images、Includes はすべて、私の 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;
}

C++ 文字列を使用するように書き直しました。ここで C 文字列を使用する理由はありません。それは今動作します。いくつかの小さな問題がありましたが、最も重大な問題は、char 配列を割り当てるときにサイズを指定しなかったことです。この行が原因でした:

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

サイズを指定しない場合、アロケーターはヒープから要求するバイト数を認識できません。あなたのプログラムはヒープ割り当てを必要としませんでした。これは、データがそれを囲むレキシカル ブロックよりも長く存続する必要がある場合がなかったからです。

于 2013-04-01T22:13:35.900 に答える