“双点” C 中的目录名?
我正在为课堂编写一个程序,我想知道一些代码的输出。我有一些这样的代码:
DIR* dir = opendir(".");
struct dirent* reader;
while ((reader = readdir(dir)) != NULL)
{
//print the name of the path found by reader.
}
现在这一切都很好,但我注意到前两个列表始终是:
.
..
//rest of files here
现在我假设第一个点 .
只是当前目录的名称,但是第二个双点是做什么用的呢?我知道 cd .. 可以让您进入文件层次结构,但我不知道为什么在读取子目录名称时会输出它。
我担心的原因是因为我想递归地遍历所有文件,但是如果我遍历..
,其中的第一个目录名称是.
,这会导致循环。那么我怎样才能避免这种情况呢?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
..
是父目录。除非您位于文件系统根目录,在这种情况下它与根目录相同。基本上,您想要检查
dir
变量是否等于.
或..
。如果是,则跳过该目录。您可以通过将该检查放入
while
循环中或通过从目录数组中过滤掉这两个目录来实现此目的。哦,请确保您不会意外跳过以
.
开头的目录,因为这些目录仍然有效。确保整个目录名称为.
或..
。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..
.当下降到目录结构时,限制递归很重要——仅忽略
.
(当前目录)和..
(父目录)是不够的(但它当然可以避免一些无用的旅行:-)。考虑一个链接到.
的符号链接文件foo
——它与下面的.
具有相同的效果。要么保留深度计数,要么保留“已看到的目录”或结构(智能实现可以检测和修剪循环)。还可以考虑使用 readlink 来检查目标。 (请注意 可以在 OS X 中创建目录的硬链接,因此 readlink 可以提供帮助,但不会忽略对其他防护的需要。)
快乐编码。
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.