如何将目录拼接成包含C中路径名的char *?

时间:2014-04-04 03:55:59

标签: c string unix char

所以现在我试图将目录名称拼接到路径名的中间。

例如,假设我想在路径中出现OTHERDIRNAME之后立即在DIRNAME中拼接。例如,让我们说道路是:

/home/user/folder/OTHERDIRNAME/morefolders/test/etc

我的目标是获得一个如下所示的新路径名:

/home/user/folder/OTHERDIRNAME/DIRNAME/morefolders/test/etc

顺便说一句,我有变量用于保存旧路径名和我希望新目录拼接到的目录名。所以我只需要在C中使用str函数来帮助尝试在正确的位置拼接DIRNAME。我尝试过使用strtok,但是我似乎遇到了使用OTHERDIRNAME作为分隔符的问题,因为我认为delimeter参数需要是一个单独的字符...

3 个答案:

答案 0 :(得分:0)

#include <stdio.h>
#include <string.h>
int main()
{
    char str[128] = "/home/user/folder/OTHERDIRNAME/morefolders/test/etc";
    char* delim = "/";
    char* tok;
    char buf[128];

    tok = strtok(str,delim);
    strcpy(buf,"/");
    while(tok)
    {
            strcat(buf,tok);
            strcat(buf,"/");
            if(strcmp(tok,"OTHERDIRNAME") == 0)
            {
                    strcat(buf,"DIRNAME");
                    strcat(buf,"/");
            }

            tok = strtok(NULL,delim);
    }

    printf("Dir path: %s\n", buf);
}

输出

Dir path: /home/user/folder/OTHERDIRNAME/DIRNAME/morefolders/test/etc/

答案 1 :(得分:0)

虽然可能令人困惑,但它非常简单。使用strstr搜索&#34;分隔符&#34;的源字符串。添加分隔符的长度,以便指向拼接的位置。然后进行3次适当长度的memcpy次调用。

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

int main(){
    char *dir = "/home/user/folder/OTHERDIRNAME/morefolders/test/etc";
    char *seek = "/OTHERDIRNAME/";
    char *ins = "DIRNAME/";
    char *splice_point;
    char *result;

    splice_point = strstr(dir, seek); // points to the first slash we're interested in
    splice_point += strlen(seek);     // now points to the second slash
    result = malloc(strlen(dir)+strlen(ins)+1);  // allocate string of appropriate length
    memcpy(result, dir, splice_point - dir);     // copy the head
    memcpy(result + (splice_point - dir), ins, strlen(ins));  // copy the splice
    strcpy(result + (splice_point - dir) + strlen(ins), splice_point);  // copy the tail (and term)

    printf("%s\n", result);
}

答案 2 :(得分:0)

你是对的,strtok将匹配第二个参数中的任何一个字符作为分隔符。

strstr()应该做你想做的事。

离开我的头顶(未经编译和未经测试):

// Returns a malloc'd null-terminated string or NULL
char * replaceInString(const char * original, const char * match, const char * replace)
{
    const char * foundMatch = strstr(original, match);
    if (foundMatch)
    {
        ptrdiff_t offset = foundMatch - original;
        int matchLength = strlen(match);
        int replaceLength = strlen(replace);

        char * newString = malloc(strlen(original) + replaceLength - matchLength + 1);
        strncpy(newString, original, offset);
        strcpy(newString + offset, replace);
        strcpy(newString + offset + replaceLength, original + offset + matchLength);

        return newString;
    }
    return NULL;
}

// snip
   char * newDirName = replaceInString(oldDirName, "/OTHERDIRNAME/", "/OTHERDIRNAME/DIRNAME/");
// snip

当然,根据您的需求调整内存管理。如果保证缓冲区足够大,你可以就地进行操作。