使用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;
}
Run Code Online (Sandbox Code Playgroud)
Alo*_*hal 10
你不应该修改argv[i].即使你这样做,你也只有一个argv[1],所以做strcat()它就会继续追随你之前的任何东西.
你有另一个微妙的错误./在大多数系统上,其中的目录名称和文件名应由路径分隔符分隔.您不要在代码中添加它.
要修复此问题,请在while循环之外:
size_t arglen = strlen(argv[1]);
Run Code Online (Sandbox Code Playgroud)
你应该在你的while循环中这样做:
/* + 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);
Run Code Online (Sandbox Code Playgroud)