[英]C++: I need help with directory navigation
So, I want to be ableto chdir into a directory, if it exists, if not make the directory. 因此,我希望能够将chdir放入目录(如果存在),如果不建立目录。 If I am already in the directory, I just don't need to do anything. 如果我已经在目录中,则无需执行任何操作。
Example 例
if (cur_dir == "dir_name")
// do stuff
else if ("dir_name" not exist?)
mkdir "dir_name"
chdir "dir_name"
else
chdir "dir_name"
I've been googling, I've come up with this so far: 我一直在使用Google搜索,到目前为止,我已经提出了以下建议:
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);
}
I haven't yet found a way to check to see what the current directory is.. (not the full path, which is what I did find.) 我还没有找到一种方法来检查当前目录是什么..(不是完整路径,这是我找到的。)
If you have Boost, you can use Boost.Filesystem : 如果您拥有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);
}
By the way, if you're just planning to read a config file, you shouldn't need to change the working directory. 顺便说一句,如果您只是打算读取配置文件,则无需更改工作目录。 Just read directly, using an absolute path. 只需使用绝对路径直接阅读即可。 In Boost.Filesystem, you'd do that this way: 在Boost.Filesystem中,您可以这样进行:
fs::path configFilePath = configFolder;
configFilePath /= "config.file";
// read configFilePath
如果您具有完整的路径,则只需解析它,然后查看最后一段(最后一个“ /”之后的部分)。
我认为getcwd()是您所需要的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.