c++ - 分割绝对文件路径

The*_*ner 1 c++ split absolute-path chdir

我正在为学校作业编写一个 C++ 程序。在某些时候,这个问题要求我更改目录,我知道该怎么做。但是,用户将为程序提供文件的绝对路径。我想做的是将目录更改为该文件所在的位置。例如,如果我在目录 dir2 中,并且用户想要转到该文件

     /home/dir1/dir2/dir3/dir4/file
Run Code Online (Sandbox Code Playgroud)

我想要做

     int ret = chdir("home/dir1/dir2/dir3/dir4");
Run Code Online (Sandbox Code Playgroud)

我的问题是如何将用户给定的字符串拆分为

     /home/dir1/dir2/dir3/dir4/
Run Code Online (Sandbox Code Playgroud)

     file
Run Code Online (Sandbox Code Playgroud)

编辑我想通了。我首先将绝对路径名从 const char* 转换为字符串。然后我使用 .find_last_of("/") 字符串成员来查找字符串中最后一个“/”的位置。然后我使用 .substr() 成员获取从 0 到 .find_last_of 返回的位置的子字符串

Huw*_*ers 7

这个问题的所有其他答案都会找到“/”(Unix)或“\”(Windows),并手动截断字符串;这是冗长的并且容易出现用户错误。C++17 现在有这个std::filesystem包,它以操作系统友好的方式从路径中干净地提取目录和文件名:

#include <filesystem>

void Test()
{
    std::filesystem::path path("/home/dir1/dir2/dir3/dir4/file");
    std::string dir = path.parent_path().string(); // "/home/dir1/dir2/dir3/dir4"
    std::string file = path.filename().string(); // "file"
}
Run Code Online (Sandbox Code Playgroud)


HSc*_*ale 6

将您的路径放入 an 中std::string,然后您可以执行如下操作。

std::string path = "/home/person/dir/file";
std::size_t botDirPos = path.find_last_of("/");
// get directory
std::string dir = path.substr(0, botDirPos);
// get file
std::string file = path.substr(botDirPos, path.length());
// change directory.
chdir(dir.c_str());
Run Code Online (Sandbox Code Playgroud)