2011-05-06 149 views
1

所以,我想能够chdir到一个目录,如果它存在,如果不使目录。如果我已经在目录中,我不需要做任何事情。C++:我需要帮助目录导航

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

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

回答

3

如果你有升压,您可以使用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 
+0

除了@波阿斯-的Yaniv如此说来改变路径,它很简单'FS ::路径p = SOME_PATH; p = new_path;'。这里是对Boost文件系统的引用(http://www.boost.org/doc/libs/1_46_1/libs/filesystem/v3/doc/reference.html)。看看“路径分配”和“路径修饰符”的链接。 – yasouser 2011-05-06 15:56:12

+0

@yasouser:忘记添加最重要的链接,谢谢。 :) – 2011-05-06 15:57:47

0

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