Search code examples
c++visual-c++dev-c++

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.


Solution

  • Editing a const string is undefined behavior, so declare something like below:

    char str[] = "D:\\Devs\\Test\\sprite.png";
    

    You can use below 1 liner to get your desired result:

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