将文件名连接到目录名称

时间:2013-12-06 10:01:30

标签: c file strcat

我想在c中添加一个目录到文件名,但是我得到一个错误:

  

分段错误(核心转储)

这是我的代码:

char fname[255];
char directoryTmp[262];

/*Working Code for entering the filename fname with fgets() */
...

/* specify the directory */ 
directoryTmp[0] = "/";
directoryTmp[1] = "f";
directoryTmp[2] = "i";
directoryTmp[3] = "l";
directoryTmp[4] = "e";
directoryTmp[5] = "s";
directoryTmp[6] = "/";

/* Copy fname at the end of directoryTmp */
strcat(directoryTmp,fname);

/* new fname with the directory, should look like: "/files/afilename */
for(i=0;i<strlen(directoryTmp);i++){
    fname[i] = directoryTmp[i];
}

//修改

好的,这是我的新代码,但我仍然得到相同的错误代码:

char fname[255];
char directory[262];

directory[sizeof(directory) - 1] = '\0';
strncpy(directory,sizeof(directory) - 1, "/files/");


for(i=0;i<strlen(directory);i++){
    fname[i] = directory[i];
}
puts(fname);

fname[sizeof(fname) - 1] = '\0';

3 个答案:

答案 0 :(得分:2)

char s放在单引号('')中,而不是双引号("")。您正在为每个数组索引分配字符串文字。

答案 1 :(得分:0)

你可以这样做

char fname[255];
char directoryTmp[262];

/*Working Code for entering the filename fname with fgets() */
...

/* specify the directory */ 
strcpy(directoryTmp,"/files/");


/* Copy fname at the end of directoryTmp */
strcat(directoryTmp,fname);

/* new fname with the directory, should look like: "/files/afilename */
for(i=0;i<strlen(directoryTmp);i++){
    fname[i] = directoryTmp[i]; //You need to take care here. Because size of the fname is 255 and size of the directoryTmp is 262. you should check length of the fname in for loop.  
}

答案 2 :(得分:0)

错误是你在填写directoryTmp时忘记了NUL终止你的字符串(在C字符串中是char的数组,按约定结束于第一个char,其值为{{ 1}})。然后,当0尝试追加strcat时,它会首先迭代fname寻找NUL字符。当数组在堆栈上初始化时(至少我从代码片段中猜测),其内容未定义,并且directoryTmp扫描超出数组末尾的未定义行为(在您的特定情况下,这会导致分段故障)。

所以,正确的代码是:

strcat

或者如其他人所述,只需使用/* specify the directory */ directoryTmp[0] = '/'; directoryTmp[1] = 'f'; directoryTmp[2] = 'i'; directoryTmp[3] = 'l'; directoryTmp[4] = 'e'; directoryTmp[5] = 's'; directoryTmp[6] = '/'; directoryTmp[7] = 0; // NUL terminate the string

strncpy

请注意,memset(directoryTmp, 0, sizeof(directoryTmp)); strncpy(directoryTmp, "/files/", sizeof(directoryTmp) - 1); does not guarantee字符串将被终止,因此我们必须自己处理。