C++:提升:需要有关目录导航逻辑的帮助

C++: Boost: Need help with directory navigation logic

本文关键字:导航 帮助 提升 C++      更新时间:2023-10-16

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

本质上:

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 ../部分。 =(

所以我的目录结构看起来像这样:


folder_name- folder_name
-- folder_name
--- folder_name

根据文档,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);

你能试试用这段代码吗?

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);
}