【问题标题】:C Recursive Directory copy of sub foldersC 子文件夹的递归目录副本
【发布时间】:2013-09-10 11:07:16
【问题描述】:

我在运行以下代码以递归复制 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
            }
        }
    }
}

}

【问题讨论】:

  • 这是一个学习如何使用调试器的好机会。

标签: c recursion copy


【解决方案1】:

似乎无法在基本目录和附加部分之间插入目录分隔符 (/)。

假设name = "/home/foo/bar"EndPtr 将指向最后的'\0',然后e->d_name 被复制到那里,中间没有任何内容。这是错误的,它会创建一个混搭的文件名。

【讨论】:

  • 所以我需要在路径和名称之间添加 / 吗?
  • 仍然无法正常工作,我已经尝试了一些方法,但其中大多数都以堆栈崩溃告终,因为我认为它是无限递归调用的。我以为我有一个很好的终止检查 if(S_ISDIR(info.st_mode)) 但它并没有停止。
【解决方案2】:

我无法自己测试您的代码,我没有安装正确的库。但是 有一个示例可能对使用 opendir 等 here 有帮助。人。

【讨论】:

    猜你喜欢
    • 2011-08-08
    • 1970-01-01
    • 2020-06-23
    • 2022-09-26
    • 2015-03-01
    • 2014-07-12
    • 2014-07-07
    • 2018-03-05
    • 1970-01-01
    相关资源
    最近更新 更多