我在运行以下代码以递归复制 C 中的子文件夹时遇到问题。我在另一篇文章中看到了这一点,但代码似乎没有运行 if 语句来检查当前文件是否为目录。
void SearchDirectory(const char *name) {
DIR *dir = opendir(name);
if(dir) {
char Path[256], *EndPtr = Path;
struct dirent *e;
strcpy(Path, name);
EndPtr += strlen(name);
while((e = readdir(dir)) != NULL) {
struct stat info;
strcpy(EndPtr, e->d_name);
if(!stat(Path, &info)) { //code stops here and won't check if the current file is a directory or not..
if(S_ISDIR(info.st_mode)) {
SearchDirectory(Path);
} else if(S_ISREG(info.st_mode) {
//Copy routine
}
}
}
}
}
编辑
所以我在路径的末尾添加了一个斜杠,它似乎找到了目录,但在执行时因堆栈错误而崩溃。我认为它是无限循环的。新代码是:
void SearchDirectory(const char *name) {
DIR *dir = opendir(name);
if(dir) {
char Path[256], *EndPtr = Path;
struct dirent *e;
strcpy(Path, name);
strcat(Path, slash);
EndPtr += (strlen(name)+1);
while((e = readdir(dir)) != NULL) {
struct stat info;
strcpy(EndPtr, e->d_name);
if(!stat(Path, &info)) { //code stops here and won't check if the current file is a directory or not..
if(S_ISDIR(info.st_mode)) {
SearchDirectory(Path);
} else if(S_ISREG(info.st_mode) {
//Copy routine
}
}
}
}
}