What is the correct way to use the stat() function to test if a DIRENT is a directory or a file?

筅森魡賤 提交于 2019-12-01 18:34:25

Yes, that's correct. But since you never change into the directory, you will not find it.

Consider the following directory hierarchy:

 a
 |
 +- b
 |  |
 |  +- c
 ...

Your code will scan its current directory, and find "a". It will determine that it is a directory, and call itself recursively, and open "a" for reading. This works. That scan will find a directory called "b", but trying to open it using the entry name only will fail, since the path is now "a/b".

I recommend changing into the directory (with chdir()) before opening it. That means you can just opendir("."). Store the old path, and chdir() out again when recursing that level is done (not before doing a recursive call to go deeper).

Where is entry defined ? is it a local variable ? I can't see why it would segfault, but may be you should make it a local variable. One example where it will bite you is here :

                    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);

The printf is gonna print the wrong name, so you should probably add an else here.

The same is true with dirpnt. When you go out of getFolderContents inside the while loop, you end up calling readdir on a closed dirpoint, which should get you out of the loop.

But as stated by bahbar : You can't recurse and store temporary variable in global variable

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!