1

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
}  
mshildt
  • 8,782
  • 3
  • 34
  • 41
SPB
  • 4,040
  • 16
  • 49
  • 62

4 Answers4

3

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

CoderDake
  • 1,497
  • 2
  • 15
  • 30
  • Actually a directory is a file in *nix. Everything is a file in *nix. See [here for more details](http://www.tldp.org/LDP/intro-linux/html/sect_03_01.html) – mshildt Oct 04 '13 at 01:03
  • @epicbrew: Yes, but directory *entries* are not files; rather, they refer to files. – Keith Thompson Oct 04 '13 at 01:13
3

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.

mshildt
  • 8,782
  • 3
  • 34
  • 41
  • ya I already did strcmp seeing it somewhere on stackoverflow. But was not knowing the explanation of .. and . . Thanks for clarifying. – SPB Oct 04 '13 at 01:09
1

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

Community
  • 1
  • 1
AlexInTown
  • 11
  • 2
0

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

alk
  • 69,737
  • 10
  • 105
  • 255