sprintf 向字符数组添加额外的字符

时间:2021-01-03 18:29:58

标签: c

我正在编写一些程序,在我的代码的某一点上,我正在浏览一个目录。为了根据路径和文件名制作一个字符串,我有这个代码:

char *aux;
aux = (char *) malloc(strlen(directory) + strlen(files[j] + 1));

sprintf(aux, "%s/%s", directory, files[j]);

//Debugging...
char b[100]; sprintf(b, "Path + file: %s\n", aux); write(1, b, strlen(b));
char c[100]; sprintf(c, "File: %s\n", files[j]); write(1, c, strlen(c));

当我执行我的程序时,我得到的输出是:

Path + file: ./Path/file.txt!
File: file.txt

如您所见,在第一个输出字符串中,文件有一个额外的字符 (!),它既不属于路径也不属于文件(如您在第二个输出字符串中所见)。我还尝试将 malloc 大小调整为不同的值,但这种情况仍然发生。为什么?

0 个答案:

没有答案