Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/c/58.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C 使用stat()函数测试DIRENT是目录还是文件的正确方法是什么?_C_Function_Directory Structure - Fatal编程技术网

C 使用stat()函数测试DIRENT是目录还是文件的正确方法是什么?

C 使用stat()函数测试DIRENT是目录还是文件的正确方法是什么?,c,function,directory-structure,C,Function,Directory Structure,“if(S_IFDIR(stbuf.st_mode))”行有一些问题。这是测试要递归到的目录的正确方法吗?目前的功能似乎在1或2个循环中都能正常工作,然后出现故障和分段错误 我试过以下方法,可能更多的是作为条件 S_ISDIR(st_mode) ((st_mode & ST_IFMT) == S_IFDIR) S_IFDIR(stbuf.st_mode) 我包含了整个函数,因为我担心问题可能在其他地方 void getFolderContents(char *source, int t

“if(S_IFDIR(stbuf.st_mode))”行有一些问题。这是测试要递归到的目录的正确方法吗?目前的功能似乎在1或2个循环中都能正常工作,然后出现故障和分段错误

我试过以下方法,可能更多的是作为条件

S_ISDIR(st_mode)
((st_mode & ST_IFMT) == S_IFDIR)
S_IFDIR(stbuf.st_mode)
我包含了整个函数,因为我担心问题可能在其他地方

void getFolderContents(char *source, int temp){
    struct stat stbuf;
    int isDir;
    dirPnt = opendir(source);
    if(dirPnt != NULL){
        while(entry = readdir(dirPnt)){
            char *c = entry->d_name;
            if(strcmp(entry->d_name, cwd) == 0 || strcmp(entry->d_name, parent) == 0){
            }
            else{
                stat(entry->d_name, &stbuf);
                printf("%i %i ", S_IFMT, stbuf.st_mode);
                if(S_IFDIR(stbuf.st_mode)){            //Test DIR or file
                printf("DIR: %s\n", entry->d_name);
                getFolderContents(entry->d_name, 0);
            }
            printf("FILE: %s\n", entry->d_name);
        }
    }
    closedir(dirPnt);
}

是的,没错。但是,由于您从未更改到该目录,因此将找不到它

考虑以下目录层次结构:

 a
 |
 +- b
 |  |
 |  +- c
 ...
您的代码将扫描其当前目录,并找到“a”。它将确定它是一个目录,并递归地调用自己,然后打开“a”进行读取。这很有效。该扫描将找到一个名为“b”的目录,但尝试仅使用条目名称打开它将失败,因为路径现在是“a/b”


我建议在打开目录之前先切换到目录(使用
)。这意味着您只需
opendir(“.”)
。存储旧路径,并在完成该级别的递归时(而不是在执行递归调用以深入之前)再次将
chdir()输出。

条目定义在哪里?它是局部变量吗? 我不明白为什么它会出错,但也许你应该把它变成一个局部变量。 它会咬你的一个例子如下:

                    if(S_IFDIR(stbuf.st_mode)){            //Test DIR or file
                            printf("DIR: %s\n", entry->d_name);
                            getFolderContents(entry->d_name, 0);
                    }
                    printf("FILE: %s\n", entry->d_name);
printf将打印错误的名称,因此您可能应该在此处添加其他名称

dirpnt也是如此。当退出while循环中的getFolderContents时, 您最终在一个闭合的dirpoint上调用readdir,这将使您脱离循环

但正如巴尔所说:
不能在全局变量

struct dirent*条目中递归和存储临时变量;这是在main()之前定义的,不能在全局函数中递归和存储临时值。把entry和dirPnt都作为本地变量Hanks Bahbar我想这会让我望而却步。它现在工作得更好了,但只会递归一个文件夹深度。哼,这不能解释SEGFAULT?当对条目结构进行测试并发现它是一个目录时,我再次递归调用该函数,该函数将打开该目录路径。您的意思是我需要包含我开始使用的目录的完整相对路径吗?您的进程正好有一个“当前目录”。所有非绝对文件操作都是以它为基础完成的。如果在“a”上执行opendir(),然后在“b”上执行opendir,那么没有任何东西可以使其表示“a/b”。您需要调用chdir()使扫描的目录成为当前目录,然后调用opendir(“.”)并递归。