假设我有以下结构:
C:\Users\User\AppData\Folder\subfolder.suffix\wanted_file.txt
Folder中只有一个.suffix子目录,但我们只知道它的前缀(名称可能不同)。wanted_file.txt?我试过这样的方法:
std::string halfpath = getenv("APPDATA");
std::string anotherhalfpath = "\\Folder\\*.suffix\\wanted_file.txt";
std::string finalpath = halfpath + anotherhalfpath;它不这样工作(它打印6-7个随机字符)。
如果我将finalpath从整个路径中删除,那么cout就会打印\\*.prefix\\wanted_file.txt,所以我认为我尝试过的语法并不好。
如果可能的话,我想要一个不需要boost的解决方案。
发布于 2015-09-23 10:12:33
如果您的环境支持文件系统TS (ISO/IEC 18822:2015)扩展,则Boost.Filesystem的功能由std::提供。
#include <experimental/filesystem>
#include <algorithm>
#include <iostream>
#include <string>
int main()
{
// APPDATA, of course, is *NOT* portable
std::path path_to_folder( getenv("APPDATA") );
path_to_folder /= "Folder";
std::directory_iterator it( path_to_folder );
std::directory_iterator end;
std::string suffix=".suffix";
while ( it != end )
{
if ( suffix.length() <= filename.length()
&&
std::equals( suffix.rbegin(), suffix.rend(), filename.rbegin() )
{
std::cout << filename << "\n";
}
++it;
}
return 0;
}据我所知,这是由MSVC 2012和Clang3.5用GCC 5.3 2015年晚些时候迎头赶上支持的。
以后的版本可能会包括<filesystem> (没有“实验性”),这将成为未来兼容的解决方案。
发布于 2015-09-23 12:51:21
只需遍历文件夹并找到带有后缀的示例:
我最喜欢的方法是使用丁香单头库,因为它简单且可移植。下面是以后缀结尾的文件夹的名称(需要C++11表示std::move,您只需去掉它):
std::string getDirWithSuffix(std::string path, std::string suffix) {
tinydir_dir dir;
std::string directory("");
if(tinydir_open(&dir, path.c_str()) == -1) {
return directory;
}
while(dir.has_next) {
tinydir_file file;
if(tinydir_readfile(&dir, &file) != -1) {
if(file.is_dir) {
std::string dirname(file.name);
// https://stackoverflow.com/questions/874134/find-if-string-endswith-another-string-in-c
if(
dirname.length() >= suffix.length() &&
dirname.compare(dirname.length() - suffix.length(), suffix.length(), suffix) == 0
) {
directory = std::move(dirname);
break;
}
}
}
tinydir_next(&dir);
}
tinydir_close(&dir);
return directory;
}https://stackoverflow.com/questions/32736019
复制相似问题