A detailed solution to the decomposition path problem based on Windows API

  • 2020-04-01 23:39:16
  • OfStack

As you can see in a lot of code, many programmers use the string lookup function in the c library to get the file name or extension in a path string. It's a lot of code and a lot of trouble.
In fact, in VC, there's a better way to get it. Without much explanation, the code is as follows:

    LPTSTR szfileName = new TCHAR[MAX_PATH];

    GetModuleFileName(NULL, szfileName , MAX_PATH);

    //Gets disk characters, file names, extensions, and so on
    wchar_t drive[_MAX_DRIVE];
    wchar_t dir[_MAX_DIR];
    wchar_t fname[_MAX_FNAME];
    wchar_t ext[_MAX_EXT];
    errno_t err;
    err = ::_wsplitpath_s(szFileName, drive, _MAX_DRIVE, dir, _MAX_DIR, 
        fname, _MAX_FNAME, ext, _MAX_EXT);
    //Just get the path
    PathRemoveFileSpec(szFileName);

Note: The _wsplitpath_s function does not change the content in the szFileName, but PathRemoveFileSpec does.
Header file: _ Wsplitpath_s () is in stdlib.h.
The PathRemoveFileSpec() function is in shlwapi.h.

Related articles: