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
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.
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.
Just loop from back to forward until you meet the first \
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.
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';
WinAPI (shlwapi) PathRemoveFileSpec should do all of that with the exception of .\file
which would come back as .