Reputation: 33
I'm writing a program for class, and I'm wondering about the output for a bit of code. I have some code like this:
DIR* dir = opendir(".");
struct dirent* reader;
while ((reader = readdir(dir)) != NULL)
{
//print the name of the path found by reader.
}
Now this works fine and all, but I notice that the first two listings are always:
.
..
//rest of files here
Now I'm assuming the first dot .
is simply the name of the current directory, but what is the second double-dot for? I know cd ..
lets you go up in the file hierarchy, but I have no clue why that is being output when reading the subdirectory names.
The reason I'm concerned is because I want to recursively go through all the files, but if I go through the ..
, the first directory name in there is .
, which causes a loop. So how can I avoid this?
Upvotes: 3
Views: 1675
Reputation:
When descending into a directory structure it is important to limit the recursion -- just ignoring .
(current directory) and ..
(parent directory) isn't enough (but it sure avoids some useless trips :-). Consider a symlink file, foo
that links to .
-- it would have the same effect as following .
.
Either keep a depth count or a "seen directory" or structure (smart implementations could detect and prune cycles). Also consider using readlink to inspect the target. (Note that hardlinks to directories can be created in OS X so readlink can help, but doesn't omit the need for other guards.)
Happy coding.
Upvotes: 2
Reputation: 35828
The ..
is the parent directory. Unless you're at the filesystem root, in which case it's the same as the root directory.
Basically you want to check to see if your dir
variable is equal to either .
or ..
. If it is, then you skip that directory.
You could achieve this by putting that check in your while
loop, or by filtering out those two directories from your array of directories.
Oh, make sure that you don't accidentally skip directories that start with .
, because those are still valid directories. Make sure that the entire directory name is .
or ..
.
Upvotes: 6