查找父文件夹的路径

时间:2013-11-21 04:42:04

标签: c string strncpy

我正在尝试解析c这样的字符串:

/afolder/secondfolder/thirdone

执行一个函数,该函数应该返回:

/afolder/secondfolder

我尝试了很多东西......

int getParentFolder(const char *pPathNewLink, char* TargetDirectory) {

    char *dirPath = strrchr(pPathNewLink, '/');

    strncpy(TargetDirectory, pPathNewLink, dirPath - pPathNewLink);

    return 1;
}

我无法使用操作系统库。我必须这样做。

我试着像这样调用函数:

char * test;
getParentFolder("/var/lib",test);
printf("%s", test);

但是我遇到了一个段错...

1 个答案:

答案 0 :(得分:1)

我想原因是你没有为test分配内存 由于您尝试strncpyTargetDirectory,因此必须将其初始化并具有内存区域。

尝试:

char *test = malloc(256);
/* or this */
char test[256];

然后做你喜欢的事情:

GetDirFromPath("/var/lib",test);
printf("%s", test);

此外,如果您选择malloc,请不要忘记在使用后将其释放:

free(test);

<强>编辑:

还有另一个问题,抱歉一开始没看到它 要复制字符串的第一部分,请使用strncpy,但是仍然需要填充字符串的结尾'\0',如下所示:

int getParentFolder(const char *pPathNewLink, char* TargetDirectory) {
    char *dirPath = strrchr(pPathNewLink, '/');
    strncpy(TargetDirectory, pPathNewLink, dirPath - pPathNewLink);
    TargetDirectory[dirPath - pPathNewLink] = 0; // please make sure there is enough space in TargetDirectory
    return 1;
}

如果还有任何问题,请告诉我。