【问题标题】:C++: Boost: Need help with directory navigation logicC++:Boost:在目录导航逻辑方面需要帮助
【发布时间】:2011-05-09 04:48:44
【问题描述】:

所以,我正在尝试更改我的目录以保存文件,然后更改回我之前所在的目录。

基本上:

cd folder_name
<save file>
cd ../

这是我目前的代码:

void save_to_folder(struct fann * network, const char * save_name)
{
    boost::filesystem::path config_folder(Config::CONFIG_FOLDER_NAME);
    boost::filesystem::path parent_folder("../");


    if( !(boost::filesystem::equivalent(config_folder, boost::filesystem::current_path())))
        {
            if( !(boost::filesystem::exists(config_folder)))
            {
                std::cout << "Network Config Directory not found...\n";
                std::cout << "Creating folder called " << Config::CONFIG_FOLDER_NAME << "\n";
                boost::filesystem::create_directory(config_folder);
            }
            boost::filesystem::current_path(config_folder);
        }

    fann_save(network, save_name);
    boost::filesystem::current_path(parent_folder);

}

目前,每次调用该方法时都会发生这种情况:
文件夹不存在:已创建
文件夹不存在:被创建

它没有做cd ../ 部分。 =(

所以我的目录结构是这样的:

文件夹名称
- 文件夹名称
-- 文件夹名称
--- 文件夹名称

【问题讨论】:

  • 我觉得可以去掉最后一行代码boost::filesystem::current_path(parent_folder);。每当您输入函数时,您都会设置要处理的文件夹的路径。
  • 我不会使用“../”作为父文件夹,而只是使用“..”。

标签: c++ boost boost-filesystem


【解决方案1】:

根据文档,current_path 方法有点危险,因为它可能会同时被其他程序修改。

所以从 CONFIG_FOLDER_NAME 操作可能会更好。

你能传递一个更大的路径名给 fann_save 吗?类似:

if( !(boost::filesystem::exists(config_folder)))
{
    std::cout << "Network Config Directory not found...\n";
    std::cout << "Creating folder called " << Config::CONFIG_FOLDER_NAME << "\n";
    boost::filesystem::create_directory(config_folder);
}
fann_save(network, (boost::format("%s/%s") % config_folder % save_name).str().c_str());

否则,如果您对使用 current_path 感到满意或无法在 fann_save 中使用更大的路径,我会尝试类似:

boost::filesystem::path up_folder((boost::format("%s/..") % Config::CONFIG_FOLDER_NAME).str());
boost::filesystem::current_path(up_folder);

【讨论】:

    【解决方案2】:

    你可以试试这个代码吗?

    void save_to_folder(struct fann * network, const char * save_name)
    {
        boost::filesystem::path configPath(boost::filesystem::current_path() / Config::CONFIG_FOLDER_NAME);
    
       if( !(boost::filesystem::exists(configPath)))
       {
           std::cout << "Network Config Directory not found...\n";
           std::cout << "Creating folder called " << Config::CONFIG_FOLDER_NAME << "\n";
           boost::filesystem::create_directory(configPath);
       }
       fann_save(network, save_name);
    }
    

    【讨论】:

      猜你喜欢
      • 2011-08-20
      • 1970-01-01
      • 1970-01-01
      • 2013-12-14
      • 2015-10-02
      • 1970-01-01
      • 1970-01-01
      • 2020-08-02
      • 1970-01-01
      相关资源
      最近更新 更多