所以现在我正在尝试将目录名称拼接到路径名的中间。
例如,假设我想在路径中出现 OTHERDIRNAME 的位置之后拼接 DIRNAME。例如,假设路径为:
/home/user/folder/OTHERDIRNAME/morefolders/test/etc
我的目标是获得如下所示的新路径名:
/home/user/folder/OTHERDIRNAME/DIRNAME/morefolders/test/etc
顺便说一下,我有用于保存旧路径名的变量以及我希望将新目录拼接到的目录的名称。所以我只需要帮助使用 C 中的 str 函数来尝试在正确的位置实际拼接 DIRNAME。我尝试使用 strtok,但我似乎遇到了使用 OTHERDIRNAME 作为分度计的问题,因为我认为分量表参数需要是一个字符......
#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: %sn", buf);
}
输出
Dir path: /home/user/folder/OTHERDIRNAME/DIRNAME/morefolders/test/etc/
这非常简单,尽管可能会令人困惑。使用 strstr
在源字符串中搜索"分隔符"。添加分隔符的长度,以便我们指向拼接的位置。然后 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("%sn", result);
}
你是对的,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
当然,根据您的需求调整内存管理。如果保证缓冲区足够大,则可以就地执行操作。