Extract base path from a pathname in C

后端 未结 8 1765
南笙
南笙 2020-12-30 14:21

Question

How do you extract the base path from pathname in C?

Are there any functions built into the C language or the C-Runtime L

相关标签:
8条回答
  • 2020-12-30 14:52

    Are there any functions built into the C language or C-Runtime to extract the base path from a pathname in C?

    No there are not. Rules for path names are platform specific and so the standard does not cover them.

    0 讨论(0)
  • 2020-12-30 14:54

    There is no standard C99 function for doing this. POSIX has dirname(), but that won't help you much on Windows. It shouldn't be too hard for you to implement your own function, though; just search through the string, looking for the last occurrence of the directory separator, and discard anything after it.

    0 讨论(0)
  • 2020-12-30 14:57

    Just loop from back to forward until you meet the first \

    0 讨论(0)
  • 2020-12-30 15:00

    In Windows you can use the API call "PathRemoveFileSpec" http://msdn.microsoft.com/en-us/library/bb773748(v=vs.85).aspx

    Cross platform solutions will not really be possible due to variations in file systems bewtween different OS's.

    0 讨论(0)
  • 2020-12-30 15:00

    Before str is the full path and file name, after str is just the path:

    char dir_ch = '\\'; // set dir_ch according to platform
    char str[] = "C:\\path\\to\\file.c";
    char *pch = &str[strlen(str)-1];
    
    while(*pch != dir_ch) pch--;
    pch++;
    *pch = '\0';
    
    0 讨论(0)
  • 2020-12-30 15:08

    WinAPI (shlwapi) PathRemoveFileSpec should do all of that with the exception of .\file which would come back as .

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