更新时间:2022-02-16 22:32:56
您不应修改argv[i]
.即使您这样做,也只有一个argv[1]
,因此对它执行strcat()
将会继续追加到先前的内容中.
You shouldn't modify argv[i]
. Even if you do, you only have one argv[1]
, so doing strcat()
on it is going to keep appending to whatever you had in it earlier.
您还有另一个细微的错误.在大多数系统上,目录名和文件名应由路径分隔符/
分隔.您无需在代码中添加它.
You have another subtle bug. A directory name and file names in it should be separated by the path separator, /
on most systems. You don't add that in your code.
要解决此问题,请在while循环之外:
To fix this, outside of your while loop:
size_t arglen = strlen(argv[1]);
您应该在while
循环中执行此操作:
You should do this in your while
loop:
/* + 2 because of the '/' and the terminating 0 */
char *fullpath = malloc(arglen + strlen(ep->d_name) + 2);
if (fullpath == NULL) { /* deal with error and exit */ }
sprintf(fullpath, "%s/%s", path, ep->d_name);
/* use fullpath */
free(fullpath);