Question

OK, so I'm trying to display all files within a given path-name. For the first path I enter, all files display correctly. However, when I use a sub-directory path as an argument to the function, it only displays a single executable (there are other files in the sub-directory as a test). I absolutely cannot figure out why this is happening. I will post the relevant snippets of code below, any help with this would be greatly appreciated.

struct dirent *directory;
DIR *pdirectory;
struct stat fileinfo;




pdirectory=opendir(path);
    if (pdirectory==NULL)
    {
            printf("Error: Unable to open directory\n");
            exit(0);
    }
    printf("%s\n",path);
    while ((directory=readdir(pdirectory)) != NULL)
    {

        if (!stat(directory->d_name,&fileinfo))
        {
            if (S_ISREG(fileinfo.st_mode))
            { 
              printf("File Name:              %s\n",directory->d_name); 
              printf("File Size:              %d bytes\n",fileinfo.st_size);
              printf("Last Access:            %s\n",ctime(&fileinfo.st_atime));
            }
            }


    }
        closedir(pdirectory);
   }
Was it helpful?

Solution

Your problem is that the stat(2) system call is failing because your not providing him with the complete path to the files located in the opened directory, in the case you are using your program to open a directory other than the current one.

This explains why your code worked only when opening the current directory.

One solution would be to append the path to the directory you're opening to the name of the file contained in the d_name member of the dirent structure such as :

/path/to/my/directory/name_of_the_file

or

path/to/my/directory/name_of_the_file

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top