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.
            Asked
            
        
        
            Active
            
        
            Viewed 174 times
        
    0
            
            
        - 
                    1[Split the string](http://stackoverflow.com/q/9210528/102937) on `/`, and take the last element in the split. – Robert Harvey May 30 '13 at 17:37
- 
                    2You want to look up the `basename()` function. – Dan Fego May 30 '13 at 17:37
- 
                    Are you looking for something like [this](http://stackoverflow.com/questions/1575278/function-to-split-a-filepath-into-path-and-file)? – A4L May 30 '13 at 17:39
5 Answers
5
            
            
        There's a function called basename that'll do just that.  See man 3 basename on how to use it.
 
    
    
        eduffy
        
- 39,140
- 13
- 95
- 92
- 
                    1Note 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
        
- 23,373
- 3
- 44
- 93
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.
 
    
    
        KrisSodroski
        
- 2,796
- 3
- 24
- 39
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
        
- 476,176
- 80
- 629
- 1,111
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,592
- 4
- 25
- 47
 
    