readdir() beginning with dots instead of files [duplicate]

我们两清 提交于 2019-11-28 07:52:45

问题


This question already has an answer here:

  • Why do directory listings contain the current (.) and parent (..) directory? 8 answers

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" ???

DIR *dir;
struct dirent *dp;
char * file_name;
while ((dp=readdir(dir)) != NULL) {

        file_name = dp->d_name;            
}

回答1:


. 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:

".\\file" - this is a file named file in current working directory

"..\\file" - this is a file in a parent directory

"..\\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).

Edit: selfcontained example usage of 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;
}



回答2:


Avoid taking the files whose name . and ..



来源:https://stackoverflow.com/questions/20265328/readdir-beginning-with-dots-instead-of-files

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