将文件与路径连接以获得C中的完整路径 [英] Concatenating file with path to get full path in C
问题描述
我使用C,试图将目录中的文件名及其路径连接起来,以便可以为每个文件调用stat(),但是当我尝试在循环内使用strcat时,它将前一个文件名与下一个文件名连接起来.它在循环中修改了argv [1],但是我已经很长时间没有使用C了,所以我很困惑...
Using C, I'm trying to concatenate the filenames in a directory with their paths so that I can call stat() for each, but when I try to do using strcat inside the loop it concatenates the previous filename with the next. It's modifying argv[1] during the loop, but I haven't worked with C in a long time, so I'm very confused...
#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()
将会继续追加到先前的内容中.
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);
这篇关于将文件与路径连接以获得C中的完整路径的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!