How to extract filename from path

后端 未结 10 1893
遥遥无期
遥遥无期 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 
    #include 
    
    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;
    
    }
    

提交回复
热议问题