Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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 :: 
");

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

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

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

}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
623 views
Welcome To Ask or Share your Answers For Others

1 Answer

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(" DIRECTORY
");
else
   printf(" FILE
");

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?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...