使用 C,我尝试将目录中的文件名与其路径连接起来,以便我可以为每个文件调用 stat() ,但是当我尝试在循环内使用 strcat 时,它将前一个文件名与下一个文件名连接起来。它在循环期间修改argv[1],但我已经很长时间没有使用C了,所以我很困惑......
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <dirent.h>
#include <string.h>
int main(int argc, char *argv[]) {
struct stat buff;
int status;
if (argc > 1) {
status = stat(argv[1], &buff);
if (status != -1) {
if (S_ISDIR(buff.st_mode)) {
DIR *dp = opendir(argv[1]);
struct dirent *ep;
char* path = argv[1];
printf("Path = %s\n", path);
if (dp != NULL) {
while (ep = readdir(dp)) {
char* fullpath = strcat(path, ep->d_name);
printf("Full Path = %s\n", fullpath);
}
(void) closedir(dp);
} else {
perror("Couldn't open the directory");
}
}
} else {
perror(argv[1]);
exit(1);
}
} else {
perror(argv[0]]);
exit(1);
}
return 0;
}
你不应该修改argv[i]
。即使你有,你也只有一个argv[1]
,这样做strcat()
它将继续附加到您之前拥有的任何内容。
你还有另一个微妙的错误。目录名和其中的文件名应该用路径分隔符分隔,/
在大多数系统上。您没有将其添加到代码中。
要解决此问题,请在 while 循环之外:
size_t arglen = strlen(argv[1]);
你应该在你的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);
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)