简体   繁体   中英

Why does readdir() list “..” as one of the files?

I am just not able to understand that why readdir() lists ".." as one of the files in the directory.
Following is my code snippet

while((dir = readdir(d)) != NULL)  
{  
    printf("%s \n", dir->d_name);  //It displayed .. once and rest of the time file names
}  

.. is not actually a file it is a directory of the *nix file system. It represents the parent directory of the current directory. Similarly . is the representation of the current dirrectory. This is relevant for moving around the file tree and relative directory representations.

Take a look at this article on changing directories :

A cd .. tells your system to go up to the directory immediately above the one in which you are currently working

The . and .. represent the current and parent directory and are present in all directories (see footnote below). readdir() does not filter them out as they are valid entries within a directory. You can do the following to filter them out yourself.

while((dir = readdir(d)) != NULL)  
{
    if (strcmp(dir->d_name, ".") == 0 || strcmp(dir->d_name, "..") == 0) {
        continue;
    }
    printf("%s \n", dir->d_name);
}

Note: Technically, SUSv3 does not require that . and .. actually be present in all directories, but does require that the OS implementation correctly interpret them when encountered within a path.

It seems readdir() does not ignore '..' & '.'. So you have to filter the two files by yourself. This post might be helpful How to recursively list directories in C on LINUX

readdir() reads the next directory entry. .. is a directory entry.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM