C语言 readdir() 以点而不是文件开头
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/20265328/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
readdir() beginning with dots instead of files
提问by user3036674
I have a little problem. I'm reading files from directory and it works, but it read two extra files on the beginning ...what is it?
for example, there is a list of files: "A348", "A348A", "A348B"and this is what i get: ".", "..", "A348", "A348A", "A348B"???
我有一个小问题。我正在从目录中读取文件并且它可以工作,但是它在开始时读取了两个额外的文件......它是什么?例如,有一个文件列表:"A348", "A348A", "A348B"这就是我得到的:".", "..", "A348", "A348A", "A348B"???
DIR *dir;
struct dirent *dp;
char * file_name;
while ((dp=readdir(dir)) != NULL) {
file_name = dp->d_name;
}
回答by nio
.is a directory entry for current directory
.是当前目录的目录项
..is a directory entry for the directory one level up in hierarchy
..是层次结构中上一级目录的目录条目
You have to just filter them out using:
您必须使用以下方法过滤掉它们:
if ( !strcmp(dp->d_name, ".") || !strcmp(dp->d_name, "..") )
{
// do nothing (straight logic)
} else {
file_name = dp->d_name; // use it
}
More on using .and ..on Windows:
有关使用.和..在 Windows 上的更多信息:
".\\file"- this is a file named filein current working directory
".\\file"- 这是file在当前工作目录中命名的文件
"..\\file"- this is a file in a parent directory
"..\\file"- 这是父目录中的文件
"..\\otherdir\\file"- this is a file that is in directory named otherdir, that is at the same level as current directory (we don't have to know what directory are we in).
"..\\otherdir\\file"- 这是一个位于名为 的目录中的文件,otherdir与当前目录处于同一级别(我们不必知道我们在哪个目录中)。
Edit: selfcontained example usage of readdir:
编辑:readdir 的自包含示例用法:
#include <stdio.h>
#include <dirent.h>
#include <string.h>
int main()
{
DIR *dir;
struct dirent *dp;
char * file_name;
dir = opendir(".");
while ((dp=readdir(dir)) != NULL) {
printf("debug: %s\n", dp->d_name);
if ( !strcmp(dp->d_name, ".") || !strcmp(dp->d_name, "..") )
{
// do nothing (straight logic)
} else {
file_name = dp->d_name; // use it
printf("file_name: \"%s\"\n",file_name);
}
}
closedir(dir);
return 0;
}
回答by Srikanth
Avoid taking the files whose name . and ..
避免取名为 . 和 ..

