将路径分成两段

时间:2012-10-11 07:30:59

标签: c

  

可能重复:
  function to split a filepath into path and file

我想将“a / b / c / directory / filename”之类的路径名拆分为“a / b / c / directory”和“filename”。在C中这样做的好方法是什么?

1 个答案:

答案 0 :(得分:0)

#include <stdio.h>
#include <string.h>
#include <stdlib.h>

int main ()
{
  char path[] ="/aaa/bbb/ccc/file";
  char *part1 = (char *)malloc (strlen(path));
  strcpy (part1, path);
  char *pos = strrchr (part1, '/');
  *pos = '\0';
  char *part2 = strdup (pos + 1);
  printf ("%s \n%s", part1, part2 );

}