Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get parent directory from file in C++

I need to get parent directory from file in C++:

For example:

Input:

D:\Devs\Test\sprite.png

Output:

D:\Devs\Test\ [or D:\Devs\Test]

I can do this with a function:

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

But, I just want to know there is exist a built-in function. I use VC++ 2003.

Thanks in advance.

like image 984
vietean Avatar asked Apr 19 '11 04:04

vietean


2 Answers

If you're using std::string instead of a C-style char array, you can use string::find_last_of and string::substr in the following manner:

std::string str = "D:\\Devs\\Test\\sprite.png";
str = str.substr(0, str.find_last_of("/\\"));
like image 62
Matt Kline Avatar answered Oct 25 '22 02:10

Matt Kline


Now, with C++17 is possible to use 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;
    }
like image 35
thakee nathees Avatar answered Oct 25 '22 02:10

thakee nathees