首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何从包含特定终止的子目录访问文件?

如何从包含特定终止的子目录访问文件?
EN

Stack Overflow用户
提问于 2015-09-23 09:38:53
回答 2查看 275关注 0票数 0

假设我有以下结构:

C:\Users\User\AppData\Folder\subfolder.suffix\wanted_file.txt

  • 我们知道在Folder中只有一个.suffix子目录,但我们只知道它的前缀(名称可能不同)。
  • 我怎么去wanted_file.txt

我试过这样的方法:

代码语言:javascript
复制
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的解决方案。

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2015-09-23 10:12:33

如果您的环境支持文件系统TS (ISO/IEC 18822:2015)扩展,则Boost.Filesystem的功能由std::提供。

代码语言:javascript
复制
#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> (没有“实验性”),这将成为未来兼容的解决方案。

票数 0
EN

Stack Overflow用户

发布于 2015-09-23 12:51:21

只需遍历文件夹并找到带有后缀的示例:

我最喜欢的方法是使用丁香单头库,因为它简单且可移植。下面是以后缀结尾的文件夹的名称(需要C++11表示std::move,您只需去掉它):

代码语言:javascript
复制
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;
}
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/32736019

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档