Alex Rivera | Logout

Get parent directory from file in C++

Asked 2011-04-19T04:13:53.777
15

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.

Edit
Report

1 Answer

23

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("/\\"));
answered 2011-04-19T04:22:45.253

Your Answer