How to extract filename from path

See char *basename(char *path).

Or run the command "man 3 basename" on your target UNIX/POSIX system.


Use basename (which has odd corner case semantics) or do it yourself by calling strrchr(pathname, '/') and treating the whole string as a basename if it does not contain a '/' character.


Here's an example of a one-liner (given char * whoami) which illustrates the basic algorithm:

(whoami = strrchr(argv[0], '/')) ? ++whoami : (whoami = argv[0]);

an additional check is needed if NULL is a possibility. Also note that this just points into the original string -- a "strdup()" may be appropriate.

Tags:

C