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");
}
One problem is that a directory is also a type of file, and can be normally
fopen()
ed. You want to calllstat()
on each file to check whether it is a directory. Like this: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 thefopen()
call?Suppose that
root/test
contains a file calledfoo
. The call todent=readdir(dir)
setsdent->d_name
to"foo"
. You already have debugging output that shows this:printf(dent->d_name)
¹. Then you try to openfoo
withfopen
, but the file is actuallyroot/test/foo
. So this fails every time (unless you happen to also have a file calledfoo
in the current directory).There are two ways to open the right file:
Construct the full name of the file by concatenating the argument to
opendir
with the file name. Something like:Change into the directory you're listing. For example, change the opendir call to
You have to remember to save the previous directory with
getcwd
andchdir
back to it afterwards. This method is not recommended in production software because it is possible to have a current directory that you can'tchdir
back into due to permissions.slacker has already explained why
fopen
can't be used to test if a file is a directory.¹ which by the way should be
puts(dent->d_name)
or even betterfputs(dent->d_name, stderr)
: your originalprintf
call would break if a file name contains%
, which is not a big problem for debugging output but is a bad habit to get into.its a combination of the two answers by slacker and Gilles. use lstat but don't use it like slacker said. You need to send lstat the full path not just dent->d_name. And just so you know lstat requires you include sys/stat.h>
if you look at the man page for lstat there is a test program at the bottom or just look at mine.
Here is my program that tries to mimick "ls" on linux. Note: escape sequence colors doesn't work in windows just in case you were worried about portability.