c++ how to remove filename from path string

前端 未结 5 1440
后悔当初
后悔当初 2020-12-09 02:53

I have

const char *pathname = \"..\\somepath\\somemorepath\\somefile.ext\";

how to transform that into

\"..\\somepath\\som         


        
相关标签:
5条回答
  • 2020-12-09 03:34

    PathRemoveFileSpec(...) you dont need windows 8 for this. you will need to include Shlwapi.h and Shlwapi.lib but they are winapi so you dont need any special SDK

    0 讨论(0)
  • 2020-12-09 03:35

    use strrchr() to find the last backslash and strip the string.

    char *pos = strrchr(pathname, '\\');
    if (pos != NULL) {
       *pos = '\0'; //this will put the null terminator here. you can also copy to another string if you want
    }
    
    0 讨论(0)
  • 2020-12-09 03:38

    On Windows use _splitpath() and on Linux use dirname()

    0 讨论(0)
  • 2020-12-09 03:49

    On Windows 8, use PathCchRemoveFileSpec which can be found in Pathcch.h

    PathCchRemoveFileSpec will remove the last element in a path, so if you pass it a directory path, the last folder will be stripped.
    If you would like to avoid this, and you are unsure if a file path is a directory, use PathIsDirectory

    PathCchRemoveFileSpec does not behave as expected on paths containing forwards slashes.

    0 讨论(0)
  • 2020-12-09 03:54

    The easiest way is to use find_last_of member function of std::string

    string s1("../somepath/somemorepath/somefile.ext");
    string s2("..\\somepath\\somemorepath\\somefile.ext");
    cout << s1.substr(0, s1.find_last_of("\\/")) << endl;
    cout << s2.substr(0, s2.find_last_of("\\/")) << endl;
    

    This solution works with both forward and back slashes.

    0 讨论(0)
提交回复
热议问题