SPB
SPB

Reputation: 4218

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
}  

Upvotes: 1

Views: 1436

Answers (4)

alk
alk

Reputation: 70981

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

Upvotes: 0

mshildt
mshildt

Reputation: 9362

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.

Upvotes: 3

AlexInTown
AlexInTown

Reputation: 11

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

Upvotes: 1

CoderDake
CoderDake

Reputation: 1547

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

Upvotes: 3

Related Questions