Как узнать, когда я нашел конец каталога подпапок? C ++ - PullRequest
0 голосов
/ 15 апреля 2020

В настоящее время я использую итератор каталога для чтения всего каталога, и он делает это хорошо, потому что он читает каждый файл в любой подпапке в каталоге.

Есть ли способ узнать, когда он достиг конца подпапки и вернется в основную папку каталога, чтобы запустить следующую?

, например, если мой каталог имеет:

mainFOLDER>SUBFOLDER>ANOTHERSUB(this is the end)
mainFOLDER>difSUBFOLDER> so on so on
mainFOLDER> whatever

Как я знаю, когда его хиты "anothersub".


        if (std::filesystem::is_directory(r)) {
            fs::path path = r.path();
            std::string path_string = path.u8string();
            if (inside == false) {
                parentDir = path_string;
            }

            double clests = processDir(path_string,inside);
            if (clests != -1) {
                string newString = to_string(clests);
                finishedPaths.push_back(newString + "   " + parentDir);
            }



        }
        else if (std::filesystem::is_regular_file(r)) {
            fs::path path = r.path();
            std::string path_string = path.u8string();
            double File = processFile(path_string);
            if (File != -1) {
                string newString = to_string(File);
                newString = newString + "   " + path_string;
                finishedPaths.push_back(newString);
            }

        }
    }

1 Ответ

0 голосов
/ 16 апреля 2020

В следующем коде я строю использование API std::filesystem, чтобы получить то, что вы просите. Пожалуйста, дайте мне знать, если я неправильно понял ваш вопрос.

Я объясняю код в комментариях.

#include <filesystem>
#include <iostream>

namespace fs = std::filesystem;
/** Print each file in the directory, separate files in different directories
 * with a horizontal line.
 */
void example1() {
  for (auto &p : fs::recursive_directory_iterator(".")) {
    if (p.is_directory()) { // We could do something fancy and stop if the
                            // p.path() is what we are looking for.
      std::cout << "--------\n";
      continue;
    }
    std::cout << p.path() << '\n';
  }
}
/** Let's recurse until we went down the first path along the Depth-First path.
 *
 * The easy way to do this, is to stop as soon as the first file is found. (See
 * <TODO>)
 *
 * But with a custom loop, we can potentially do more.
 */
void example2() {
  auto it = fs::recursive_directory_iterator(".");
  while (it != end(it)) { // Note: fs::end(...) argument is ignored.
    std::cout << it->path() << "\t" << it.depth() << "\n";
    /* 1. it++: This moves to the next entry. That's the default thing to do.
     * 2. it.pop(). "moves the iterator one level up in the directory hierarchy"
     * This might be useful if we are looking for specific files, and want to
     * continue in the next directory.
     * 3. it.disable_recursion_pending(): It means that it won't go into
     * subdirectories.
     */
    it++; // Code style: If we always just increment it, for(it; it!=end(it);
          // it++) is better than a while loop.
  }
}
/** If I understood this correctly, you want to stop as soon you hit a directory
 * named 'anothersub'.
 */
void example3() {
  for (auto it = fs::recursive_directory_iterator("."); it != end(it); it++) {
    const auto p = it->path();
    if (it->is_directory() and p.filename() == "anothersub") {
      break;
    }
    std::cout << p << "\n";
  }
}
int main() {
  example1();
  example2();
  example3();
}

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

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

...