【问题标题】:How to access the relative parent directory using <filesystem> in C++如何在 C++ 中使用 <filesystem> 访问相对父目录
【发布时间】:2019-10-21 00:30:02
【问题描述】:

我想知道如何使用C++ 17&lt;filesystem&gt; 标头访问当前工作目录的父目录。然后我想从父目录重定向到另一个文件夹来搜索文件。

这是一个概念性示例:

#include <iostream>
#include <filesystem>
using namespace std;

int main()
{
    namespace fs = std::filesystem;

    fs::path working_dir(fs::current_path());

    fs::path parent_path(
        // ... Get path to parent dir of current working dir ... //
        );

    fs::current_path(parent_path);
    fs::current_path(
        // ... Redirect to subfolder called "sub_fold" ... //
        );

    // ... Search for specified file called "sub_file" to see if it exists ... //
    if (sub_file.exists())  // Psudo-code for returning if "sub_file" exists
    {
        // ... Do stuff with "sub_file" ... //
    }
    else cout << "File does not exist in " << fs::current_path << endl;

    fs::current_path(working_dir);

    // ... Continue program ... //
    return 0;
}

【问题讨论】:

    标签: c++ file directory c++17


    【解决方案1】:

    working_dir.parent_path() 会将您带到父目录 - 但请务必先检查它是否存在。

    working_dir / "sub_fold" 应该会带您进入子目录。

    此信息由cppreference.com提供

    【讨论】:

    • 谢谢。关于第二部分,具体语法类似于fs::current_path(working_dir.parent_path() / "sub_fold"); 对吧?
    • 您需要正确声明变量。例如,fs::path current_path 声明了一个名为 current_path 的变量,其类型为 fs::path。据我所知,没有fs::current_path 电话。
    猜你喜欢
    • 2015-07-07
    • 2011-10-25
    • 1970-01-01
    • 1970-01-01
    • 2010-12-28
    • 2011-04-25
    • 2012-01-25
    • 2015-11-08
    • 2011-04-01
    相关资源
    最近更新 更多