How to extract filename from path

后端 未结 10 1845
遥遥无期
遥遥无期 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:47

    You can escape slashes to backslash and use this code:

    #include <stdio.h>
    #include <string.h>
    
    int main(void)
    {
      char path[] = "C:\\etc\\passwd.c"; //string with escaped slashes
      char temp[256]; //result here
      char *ch; //define this
      ch = strtok(path, "\\"); //first split
      while (ch != NULL) {
          strcpy(temp, ch);//copy result
          printf("%s\n", ch);
          ch = strtok(NULL, "\\");//next split
      }
    
      printf("last filename: %s", temp);//result filename
    
      return 0;
    
    }
    
    0 讨论(0)
  • 2020-12-15 03:48

    My example (improved):

        #include <string.h>
    
        const char* getFileNameFromPath(const char* path, char separator = '/')
        {
            if(path != nullptr)
            {
                for(size_t i = strlen(path);  i > 0; --i)
                {
                    if (path[i-1] == separator)
                    {
                        return &path[i];
                    }
                }
            }
        
            return path;
        }
    
    0 讨论(0)
  • 2020-12-15 03:50

    The basename() function returns the last component of a path, which could be a folder name and not a file name. There are two versions of the basename() function: the GNU version and the POSIX version.

    The GNU version can be found in string.h after you include #define _GNU_SOURCE:

        #define _GNU_SOURCE
    
        #include <string.h>
    

    The GNU version uses const and does not modify the argument.

        char * basename (const char *path)

    This function is overridden by the XPG (POSIX) version if libgen.h is included.

        char * basename (char *path)

    This function may modify the argument by removing trailing '/' bytes. The result may be different from the GNU version in this case:

        basename("foo/bar/")

    will return the string "bar" if you use the XPG version and an empty string if you use the GNU version.

    References:

      basename (3) - Linux Man Pages
      Function: char * basename (const char *filename), Finding Tokens in a String.

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

    See char *basename(char *path).

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

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