0

For example, I have a string"/home/george/file.c", I want to cut the string to be "file.c", so just get rid of all string before the last '/' character.

Makoto
  • 100,191
  • 27
  • 181
  • 221
georgewhr
  • 144
  • 1
  • 12

5 Answers5

5

There's a function called basename that'll do just that. See man 3 basename on how to use it.

eduffy
  • 37,790
  • 12
  • 92
  • 91
  • 1
    Note that `basename` is not part of the c standard library, though it is very widely available. The man page on my mac claims *"The basename() function conforms to X/Open Portability Guide Issue 4, Version 2 (``XPG4.2'')."* – dmckee --- ex-moderator kitten May 30 '13 at 18:27
1

Here, it is possible to use strrchr from <string.h> header. Look at its documentation.

#include <string.h>

char *end = strrchr(string, '/') + 1;
char result[SIZE];

if (end != NULL)
    strcpy(result, end);
md5
  • 22,897
  • 3
  • 42
  • 92
0

If you're using the string library, you can just get the length of the string, then start walking backwards until you hit your first '/' character. Then, take that index and use substring.

Magn3s1um
  • 2,758
  • 3
  • 21
  • 36
0
char *filename = strrchr(path, '/'); // this points `filename` at the final '/'
if (filename)                        // if that succeeded
   ++filename;                       //     we want the next character
else                                 // otherwise
     filename = path;                //     what's in path is all the file name.
Jerry Coffin
  • 455,417
  • 76
  • 598
  • 1,067
0

You can use the basename() defined in the header file <libgen.h> . The prototype of basename() is char *basename(const char *fname);. It returns a pointer into the original file name where the basename starts.

In your case the code should be as follows,

char ch="/home/george/file.c"
char *ptr;
ptr=basename(ch);
printf("The file name is %s",ptr);
Deepu
  • 7,534
  • 4
  • 24
  • 47