How to extract filename from path

后端 未结 10 1844
遥遥无期
遥遥无期 2020-12-15 03:26

There should be something elegant in Linux API/POSIX to extract base file name from full path

相关标签:
10条回答
  • 2020-12-15 03:31

    @Nikolay Khilyuk offers the best solution except.

    1) Go back to using char *, there is absolutely no good reason for using const.

    2) This code is not portable and is likely to fail on none POSIX systems where the / is not the file system delimiter depending on the compiler implementation. For some windows compilers you might want to test for '\' instead of '/'. You might even test for the system and set the delimiter based on the results.

    The function name is long but descriptive, no problem there. There is no way to ever be sure that a function will return a filename, you can only be sure that it can if the function is coded correctly, which you achieved. Though if someone uses it on a string that is not a path obviously it will fail. I would have probably named it basename, as it would convey to many programmers what its purpose was. That is just my preference though based on my bias your name is fine. As far as the length of the string this function will handle and why anyone thought that would be a point? You will unlikely deal with a path name longer than what this function can handle on an ANSI C compiler. As size_t is defined as a unsigned long int which has a range of 0 to 4,294,967,295.

    I proofed your function with the following.

        #include <stdio.h>
        #include <string.h>
    
        char* getFileNameFromPath(char* path);
    
        int main(int argc, char *argv[])
        {
            char *fn;
    
            fn = getFileNameFromPath(argv[0]);
            printf("%s\n", fn);
            return 0;
        }
    
        char* getFileNameFromPath(char* path)
        {
           for(size_t i = strlen(path) - 1; i; i--)  
           {
                if (path[i] == '/')
                {
                    return &path[i+1];
                }
            }
            return path;
        }
    

    Worked great, though Daniel Kamil Kozar did find a 1 off error that I corrected above. The error would only show with a malformed absolute path but still the function should be able to handle bogus input. Do not listen to everyone that critiques you. Some people just like to have an opinion, even when it is not worth anything.

    I do not like the strstr() solution as it will fail if filename is the same as a directory name in the path and yes that can and does happen especially on a POSIX system where executable files often do not have an extension, at least the first time which will mean you have to do multiple tests and searching the delimiter with strstr() is even more cumbersome as there is no way of knowing how many delimiters there might be. If you are wondering why a person would want the basename of an executable think busybox, egrep, fgrep etc...

    strrchar() would be cumbersome to implement as it searches for characters not strings so I do not find it nearly as viable or succinct as this solution. I stand corrected by Rad Lexus this would not be as cumbersome as I thought as strrchar() has the side effect of returning the index of the string beyond the character found.

    Take Care

    0 讨论(0)
  • 2020-12-15 03:37

    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.

    0 讨论(0)
  • 2020-12-15 03:37
    template<typename charType>
    charType* getFileNameFromPath( charType* path )
    {
        if( path == NULL )
            return NULL;
    
        charType * pFileName = path;
        for( charType * pCur = path; *pCur != '\0'; pCur++)
        {
            if( *pCur == '/' || *pCur == '\\' )
                pFileName = pCur+1;
        }
        
        return pFileName;
    }
    

    call: wchar_t * fileName = getFileNameFromPath < wchar_t > ( filePath );

    (this is a c++)

    0 讨论(0)
  • 2020-12-15 03:38

    Of course if this is a Gnu/Linux only question then you could use the library functions.

    https://linux.die.net/man/3/basename

    And though some may disapprove these POSIX compliant Gnu Library functions do not use const. As library utility functions rarely do. If that is important to you I guess you will have to stick to your own functionality or maybe the following will be more to your taste?

    #include <stdio.h>
    #include <string.h>
    
    int main(int argc, char *argv[])
    {
        char *fn;
        char *input;
    
        if (argc > 1)
            input = argv[1];
        else
            input = argv[0];
    
        /* handle trailing '/' e.g. 
           input == "/home/me/myprogram/" */
        if (input[(strlen(input) - 1)] == '/')
            input[(strlen(input) - 1)] = '\0';
    
        (fn = strrchr(input, '/')) ? ++fn : (fn = input);
    
    
        printf("%s\n", fn);
        return 0;
    }
    
    0 讨论(0)
  • 2020-12-15 03:44

    You could use strstr in case you are interested in the directory names too:

    char *path ="ab/cde/fg.out";
    char *ssc;
    int l = 0;
    ssc = strstr(path, "/");
    do{
        l = strlen(ssc) + 1;
        path = &path[strlen(path)-l+2];
        ssc = strstr(path, "/");
    }while(ssc);
    printf("%s\n", path);
    
    0 讨论(0)
  • 2020-12-15 03:47

    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.

    0 讨论(0)
提交回复
热议问题