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

自作多情 提交于 2019-11-29 14:21:38
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:

".\\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;
}

Avoid taking the files whose name . and ..

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