c - 查找父文件夹的路径

标签 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);

但是我遇到了段错误...

最佳答案

我想原因是您没有为测试分配内存
由于您尝试 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;
}

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

关于c - 查找父文件夹的路径,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20112665/

相关文章:

c - 遍历 C 字符串 : get the last word of a string

从 Matlab 调用 Fortran 中的 C 兼容 DLL

c - 为什么整数 `j` 返回 `i` ?

c - 如何从 c 调用回调 tcl 过程

python - 加速 Python NLP 文本解析

python - 如何将字符串中每个单词的第一个字符大写?

objective-c - 在 Objective-C 中我可以将属性视为数组吗?

c# - 评估转义字符串

C: 创建自己的 strncpy 版本

使用分配的内存将整数复制到整数