发现C ++文件

时间:2018-11-03 09:48:39

标签: c++

如何在C ++和所有Windows驱动程序中找到具有特定扩展名的文件列表

例如在python中:

import os

def discoverFiles(startpath): extensions = [ 'rar','pdf','mp3' ]

for dirpath, dirs, files in os.walk(startpath):
    for i in files:
        absolute_path = os.path.abspath(os.path.join(dirpath, i))
        ext = absolute_path.split('.')[-1]
        if ext in extensions:
            yield absolute_path

x = discoverFiles('/') for i in x: print i


Test my script for better understanding

请帮助我使用Windows api代码或C ++内部库

2 个答案:

答案 0 :(得分:4)

这可以使用C ++ 17及更高版本中的标准库file_system组件,在跨平台的庄园中实现:https://en.cppreference.com/w/cpp/filesystem。在此之前,可以通过Boost(https://www.boost.org/doc/libs/1_68_0/libs/filesystem/doc/index.htm)或文件系统技术规范(在std :: experimental名称空间中)获得file_system实现

#include <filesystem>
#include <iostream>
#include <iterator>

namespace fs = std::filesystem;

auto discoverFiles(fs::path start_path)
{
    std::vector<std::string> extensions = { ".rar", ".pdf", ".mp3" };
    std::vector<std::string> files;
    for (const auto& path : fs::recursive_directory_iterator(start_path))
    {
        if (std::find(extensions.begin(), extensions.end(), path.path().extension()) != extensions.end())
        {
            files.push_back(path.path().string());
        }
    }
    return files;
}

int main(int argc, char *argv[])
{
    auto files = discoverFiles( fs::current_path().root_path() );
    std::copy(files.begin(), files.end(), std::ostream_iterator<std::string>(std::cout, 
"\n"));
}

需要注意的几点是,这与您的python实现不同,因为它无法访问yield关键字。这样的结果是预先计算的,而不是像Python中那样推迟到其使用点,这可能会影响内存使用和性能。一旦C ++可以访问协例程,然后可以在该语言中实现yield语义,这种情况将来可能会改变(正在讨论如何将其包含在C ++ 20中,但尚待观察是否会使它成为现实)。将其添加到此语言版本中)

此外,它已在Windows上进行了测试,该Windows不喜欢从驱动器的根目录递归扫描,并引发了访问异常。但是,在根目录下指定任何文件夹都会导致其正常工作。

答案 1 :(得分:2)

在Windows上,您可以使用FindFirstFile()

在* nix上为glob()。与问题中的原始Python代码相比,哪个also exists in Python可能更适合此问题。