Search code examples
cunixstat

stat() error 'No such file or directory' when file name is returned by readdir()


I'm not able to identify the error thrown by stat. The below program reads all files in a directory and prints the file name:

DIR *dp;
struct dirent *dirp;
struct stat sb;

if((dp = opendir(argv[1]))==NULL)
{
    perror("can't open dir");
}
while((dirp = readdir(dp))!=NULL)
{
    if (stat(dirp->d_name, &sb) == -1) {
        perror("stat");
    }   
    printf("File name:               %s \n",dirp->d_name);
}

Sample output:

/home/eipe
stat error: No such file or directory
File name:               copyofsample 
File name:               a.out 
File name:               . 
stat error: No such file or directory
File name:               udpclient.c 
File name:               .. 
stat error: No such file or directory
File name:               client.c 
stat error: No such file or directory
File name:               ftpclient.c 

Here are the contents:

ls -l /home/eipe/c

-rwxr-xr-x 1 eipe egroup 7751 2011-02-24 15:18 a.out
-rw-r--r-- 1 eipe egroup  798 2011-02-24 13:50 client.c
-rw-r--r-- 1 eipe egroup   15 2011-02-24 15:34 copyofsample
-rw-r--r-- 1 eipe egroup 1795 2011-02-24 15:33 ftpclient.c
-rw-r--r-- 1 eipe egroup  929 2011-02-24 13:34 udpclient.c

Solution

  • dirp->d_name is the name of the file in the directory: for example, "udpclient.c". The full name of the file is thus "/home/eipe/c/udpclient.c" - but your current working directory is /home/eipe, so stat() is trying to access "/home/eipe/udpclient.c", which doesn't exist.

    You can either change your working directory to argv[1] using chdir(), or you can prepend argv[1] to each filename before you call stat().