如何按文件扩展名引用文件夹中的文件

How to refer to files in folder by file extension

本文关键字:文件 文件夹 引用文 引用 何按 扩展名      更新时间:2023-10-16

我正在将一个表示文件夹路径的字符串作为参数传递给构造函数。

文件夹名称、其中的文件及其名称可能会有所不同,但两个文件的扩展名始终相同:*.caffemodel*.prototxt.

如何使用扩展名引用指定目录中的这两个文件,而无需扫描整个文件夹以获取其完整名称?

举个例子,这是我类的代码:

#include "NeuralClassifier.hpp"

NeuralClassifier::NeuralClassifier(std::string path)
{
std::string modelName = path + "/*.caffemodel";
std::string protoName = path + "/*.prototxt";
cv::dnn::Net net;
try {
net = dnn::readNetFromCaffe(protoName, modelName);
}
catch (cv::Exception& e) {
std::cerr << "Exception: " << e.what() << std::endl;
if (net.empty())
{
std::cerr << "Can't load network by using the following files: " << std::endl;
std::cerr << "prototxt:   " << protoName << std::endl;
std::cerr << "caffemodel: " << modelName << std::endl;
std::cerr << "bvlc_googlenet.caffemodel can be downloaded here:" << std::endl;
std::cerr << "http://dl.caffe.berkeleyvision.org/bvlc_googlenet.caffemodel" << std::endl;
exit(-1);
}
}
}

在某些时候,操作系统需要知道应用程序要打开的确切文件名。在您的情况下,您指定一个通配符"*",该通配符可以不与多个文件匹配。

如果你只想打开与通配符匹配的第一个文件,你可以使用 boost::filesystem 来简化文件处理:

我可以使用掩码在带有 Boost 的目录中迭代文件吗?