【问题标题】:C++: I need help with directory navigationC++:我需要目录导航方面的帮助
【发布时间】:2011-08-20 07:10:06
【问题描述】:

所以,我希望能够 chdir 进入一个目录,如果它存在,如果不存在的话。如果我已经在目录中,我不需要做任何事情。

例子

if (cur_dir == "dir_name")
// do stuff
else if ("dir_name" not exist?)
   mkdir "dir_name"
   chdir "dir_name"
else
   chdir "dir_name"

我一直在谷歌搜索,到目前为止我想出了这个:

if (chdir(Config::CONFIG_FOLDER_NAME) == 0)
{
    std::cout << "Network Config Directory not found...\n";
    std::cout << "Creating folder called " << Config::CONFIG_FOLDER_NAME << "\n";
    mkdir(Config::CONFIG_FOLDER_NAME, 0777);
}

我还没有找到一种方法来检查当前目录是什么..(不是完整路径,这是我找到的。)

【问题讨论】:

    标签: c++ file-io directory


    【解决方案1】:

    如果你有 Boost,你可以使用Boost.Filesystem:

    namespace fs = boost::filesystem;
    
    fs::path configFolder(Config::CONFIG_FOLDER_NAME);
    
    // Check if the current directory isn't already config folder
    if (!fs::equivalent(configFolder, fs::current_path())
    {
        // Create config folder if it doesn't exist
        if (!fs::exists(configFolder))
           fs::create_directory(configFolder);
    
        // Change working directory to config folder
        fs::current_path(configFolder);
    }
    

    顺便说一句,如果您只是打算读取配置文件,则不需要更改工作目录。直接阅读,使用绝对路径。在 Boost.Filesystem 中,您可以这样做:

    fs::path configFilePath = configFolder;
    configFilePath /= "config.file";
    
    // read configFilePath
    

    【讨论】:

    • 除了@Boaz-Yaniv 所说的:改变路径,很简单fs::path p = some_path; p = new_path;。这是对 Boost Filesystem (boost.org/doc/libs/1_46_1/libs/filesystem/v3/doc/reference.html) 的参考。查看显示“路径分配”和“路径修饰符”的链接。
    • @yasouser:忘记添加最重要的链接,谢谢。 :)
    【解决方案2】:

    如果你有完整路径,那么只需解析它并查看最后一段(最后一个“/”之后的部分)。

    【讨论】:

      【解决方案3】:

      我认为getcwd() 是您所需要的。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-01-02
        • 1970-01-01
        相关资源
        最近更新 更多