H1rouge
H1rouge

Reputation: 81

What does '.' signify in c as argument to opendir?

"This is the code. What is the meaning of '.' inside "opendir('.')" Does it specifies to the current directory?"

#include <stdio.h> 
#include <dirent.h> 
int main(void) 
{ 
struct dirent *de;  // Pointer for directory entry 

// opendir() returns a pointer of DIR type.  
DIR *dr = opendir("."); 

if (dr == NULL)  // opendir returns NULL if couldn't open directory 
{ 
    printf("Could not open current directory" ); 
    return 0; 
} 


while ((de = readdir(dr)) != NULL) 
        printf("%s\n", de->d_name); 

closedir(dr);     
return 0; 
} 

Upvotes: 2

Views: 631

Answers (2)

Some programmer dude
Some programmer dude

Reputation: 409442

This isn't really programming-related, but more OS-related.

On most operating systems the filesystem have the concept of parent directory and current directory.

The parent directory is commonly using the notation .., while the current directory is using the notation ..

So what opendir(".") will do is to open the current directory.


And as mentioned in a comment, the "current" directory doesn't have to be the directory where the executable program is residing. It's the current working directory for the process, which could be different. It depends on how and where the program was started, and if the program changes its own working directory (which the program in the question doesn't).

Upvotes: 7

Achal
Achal

Reputation: 11931

Here

DIR *dr = opendir("."); 

. represents the current directory and .. represents the parent directory, here opendir() tries to open the current directory & if success it return a pointer to the directory stream.

from the manual page of opendir

The opendir() function shall open a directory stream corresponding to the directory named by the dirname argument. The directory stream is positioned at the first entry.

On most of linux machines, first two entries in a directory are current . and parent ... If you run a ls command in a given directory it shows like

[root@try]# ls -lia
total 28
425985 drwxr-xr-x. 2 root root  4096 Jan 30 10:29 .       <--- current dir inode
393284 drwxr-xr-x. 3 root root 20480 Jan 30 10:28 ..      <--- parent dir inode
407821 -rw-r--r--. 1 root root     0 Jan 30 10:29 demo.c

Upvotes: 2

Related Questions