Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to remove the path to get the filename

Tags:

c

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.

like image 589
some_id Avatar asked Dec 07 '22 16:12

some_id


2 Answers

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.

like image 73
R.. GitHub STOP HELPING ICE Avatar answered Dec 09 '22 04:12

R.. GitHub STOP HELPING ICE


You want basename(3).

like image 27
Carl Norum Avatar answered Dec 09 '22 04:12

Carl Norum