Related questions
How can I detect the operating system in C/C++?
How can I find out what operating system I am runni
Here is what I ended up with:
#include
/*
NAME
basename -- return pointer to last component of a pathname
Distribution: This function is in the public domain.
Origin of function:
http://www.koders.com/c/fidEB79B7607A210C3BB7B813E793465F9D469AE912.aspx
SYNOPSIS
char *basename (const char *name)
DESCRIPTION
Given a pointer to a string containing a typical pathname
(/usr/src/cmd/ls/ls.c for example), returns a pointer to the
last component of the pathname ("ls.c" in this case).
Restrictions:
Presumes a UNIX or DOS/Windows style path with UNIX or DOS/Windows
style separators.
*/
/*
NAME:
basename:
Function:
return pointer to last component of a pathname
Distribution:
This function is in the public domain.
Origin of function:
http://www.koders.com/c/fidEB79B7607A210C3BB7B813E793465F9D469AE912.aspx
SYNOPSIS:
char *basename (const char *name)
DESCRIPTION:
Given a pointer to a string containing a typical pathname
(/usr/src/cmd/ls/ls.c for example), returns a pointer to the
last component of the pathname ("ls.c" in this case).
Restrictions:
Presumes a UNIX or DOS/Windows style path with UNIX or
DOS/Windows style separators.
Windows volumes are only a-zA-Z.
The original code suggests ISALPHA.
*/
char * basename (const char *name)
{
const char *base;
// predefined OS symbols
// http://sourceforge.net/apps/mediawiki/predef/index.php?title=Operating_Systems#UNIX_Environment
#ifndef DIR_SEPARATOR
# define DIR_SEPARATOR '/'
#endif
#ifndef DIR_SEPARATOR_2
# define DIR_SEPARATOR_2 '\\'
#endif
// Check if we are running Unix like os
// else assume Windows. Note if we guess wrong, it's not
// so bad because Windows includes the Unix separator.
#if defined (__unix__) || (defined (__APPLE__) && defined (__MACH__))
# define IS_DIR_SEPARATOR(ch) ((ch) == DIR_SEPARATOR)
#else
# define IS_DIR_SEPARATOR(ch) \
(((ch) == DIR_SEPARATOR) || ((ch) == DIR_SEPARATOR_2))
/* Skip over the disk name in MSDOS pathnames. */
if (isalpha(name[0]) && name[1] == ':')
name += 2;
#endif
for (base = name; *name; name++)
{
if (IS_DIR_SEPARATOR (*name))
{
base = name + 1;
}
}
return (char *) base;
}
int main (int argc, const char * argv[]) {
/* Return the basename of a pathname. */
#define S1 "/usr/src/cmd/ls/ls.c"
#define S2 "/usr/src/cmd/ls/abc"
#define S3 "a:/usr/src/cmd/ls/def"
#define S4 "ghi"
#define S5 "jkl.txt"
#define S6 "d:\\usr\\src\\cmd\\mno.txt"
#define S7 "d:pqm.txt"
printf(S1 " \t is %s\n",basename(S1));
printf(S2 " \t is %s\n",basename(S2));
printf(S3 " \t is %s\n",basename(S3));
printf(S4 " \t is %s\n",basename(S4));
printf(S5 " \t is %s\n",basename(S5));
printf(S6 " \t is %s\n",basename(S6));
printf(S7 " \t is %s\n",basename(S7));
return 0;
}