从C++中的文件获取父目录

vie*_*ean 5 c++ dev-c++ visual-c++

我需要从C++中的文件中获取父目录:

例如:

输入:

D:\Devs\Test\sprite.png
Run Code Online (Sandbox Code Playgroud)

输出:

D:\Devs\Test\ [or D:\Devs\Test]
Run Code Online (Sandbox Code Playgroud)

我可以用一个函数做到这一点:

char *str = "D:\\Devs\\Test\\sprite.png";
for(int i = strlen(str) - 1; i>0; --i)
{
    if( str[i] == '\\' )
    {
        str[i] = '\0';
        break;
    }
}
Run Code Online (Sandbox Code Playgroud)

但是,我只是想知道存在一个内置函数.我使用VC++ 2003.

提前致谢.

tha*_*ees 15

现在,使用 C++17 可以使用std::filesystem::path::parent_path

    #include <filesystem>
    namespace fs = std::filesystem;

    int main() {
        fs::path p = "D:\\Devs\\Test\\sprite.png";
        std::cout << "parent of " << p << " is " << p.parent_path() << std::endl;
        // parent of "D:\\Devs\\Test\\sprite.png" is "D:\\Devs\\Test"

        std::string as_string = p.parent_path().string();
        return 0;
    }
Run Code Online (Sandbox Code Playgroud)


Mat*_*ine 12

如果您使用的是std :: string而不是C样式的char数组,则可以按以下方式使用string :: find_last_ofstring :: substr:

std::string str = "D:\\Devs\\Test\\sprite.png";
str = str.substr(0, str.find_last_of("/\\"));
Run Code Online (Sandbox Code Playgroud)

  • 我喜欢这个答案,但我认为它需要解决如果找不到目录分隔符则返回的“string::npos”问题。因此,如果找到目录分隔符,则父目录路径最终将成为文件路径。我认为应该检查 `string::npos` ,如果找不到分隔符则返回 `.` 。 (2认同)

iam*_*ind 3

编辑 const 字符串是未定义的行为,因此声明如下:

char str[] = "D:\\Devs\\Test\\sprite.png";
Run Code Online (Sandbox Code Playgroud)

您可以使用以下 1 种内衬来获得您想要的结果:

*(strrchr(str, '\\') + 1) = 0; // put extra NULL check before if path can have 0 '\' also
Run Code Online (Sandbox Code Playgroud)