Accessing Directories in C

Vinod K picture Vinod K · Aug 21, 2010 · Viewed 20.1k times · Source

The program is to open a directory and to display the name of the files... i.e if there is a file..it should say FILE....else DIRECTORY.. but the program displays all the files as directory..

Could anyone pls check the code for any errors....thnx

#include<stdio.h>
#include<dirent.h>
#define DIR_path "root/test"      
main()
 {
   DIR *dir;
   dir=opendir(DIR_PATH);
   printf("THe files inside the directory :: \n");

  struct dirent *dent;
  if(dir!=NULL)
   {

       while((dent=readdir(dir)))
         {
            FILE *ptr;
            printf(dent->d_name);

              if(ptr=fopen(dent->d_name,"r"))
                {
                     print("\tFILE\n");
                     fclose(ptr);
                }
              else
                    printf("\t DIRECTORY\n");
        }
           close(dir);
    }
    else
            printf("ERROR OPENIN DIRECTORY");

}

Answer

slacker picture slacker · Aug 21, 2010

One problem is that a directory is also a type of file, and can be normally fopen()ed. You want to call lstat() on each file to check whether it is a directory. Like this:

struct stat st;
lstat(dent->d_name, &st);
if(S_ISDIR(st.st_mode))
   printf("\t DIRECTORY\n");
else
   printf("\t FILE\n");

But this error should lead to all entries being displayed as files. Do you have read permissions for the files in this directory? What is the value of errno after the fopen() call?