How does one remove the path of a filepath, leaving only the filename?
I want to extract only the filename from a fts_path and store this in a char *fileName.
Here's a function to remove the path on POSIX-style (/
-separated) pathnames:
char *base_name(const char *pathname)
{
char *lastsep = strrchr(pathname, '/');
return lastsep ? lastsep+1 : pathname;
}
If you need to support legacy systems with odd path separators (like MacOS 9 or Windows), you might need to adapt the above to search for multiple possible separators. For example on Windows, both /
and \
are path separators and any mix of them can be used.
You want basename(3)
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With