Link to home
Start Free TrialLog in
Avatar of shepson990
shepson990

asked on

directory listing

hi

i have the code below which prints the contents of a directory specified in dp.

main()
{
        DIR *dp = opendir(".");
        struct dirent *d;

        while ((d = readdir(dp)) != NULL)
        {
                printf("%s\n", d->d_name);
        }
 
        closedir(dp);

when it prints the contents it will also print a "." and "..". So i want to  be able to do something like the following, so it doesnot print ".,;". but his does not work. Any ideas

       while ((d = readdir(dp)) != NULL)
        {
               while(strpbrk(d->d_name,".,;"){
                        printf("%s\n", d->d_name);
               }
        }

        closedir(dp);



}
Avatar of sunnycoder
sunnycoder
Flag of India image

. and .. are the only two special directories that you are likely to encounter ...
. means current directory
.. means parent directory

        while ((d = readdir(dp)) != NULL)
        {
                if ( strcmp (d->d_name, ".") != 0 && strcmp (d->d_name, "..") )
                          printf("%s\n", d->d_name);
        }
Avatar of shepson990
shepson990

ASKER

how would i get the following to work
while ((d = readdir(dp)) != NULL)
{
      if ( strcmp (d->d_name, ".") != 0 && strcmp (d->d_name, "..") )
        sprintf(szBuf2,"/home/shepson/netstatus/errors/%s",d->d_name);
      read=fopen(szBuf2,"r");          
      printf("%s\n", read);
}
 
sprintf(szBuf2,"/home/shepson/netstatus/errors/%s",d->d_name);
     read=fopen(szBuf2,"r");          
     printf("%s\n", read);

fopen returns a file handle !!! Why would you like to print the file handle ? What are you trying to do ? Also if fopen fails, it will return NULL and you will try to print NULL ?
Another thing, read is a system call and be careful when you use it as a variable name
Since you may not be interested in opening . and .., you can include the fopen in the if block

while ((d = readdir(dp)) != NULL)
{
     if ( strcmp (d->d_name, ".") != 0 && strcmp (d->d_name, "..") )
     {
          sprintf(szBuf2,"/home/shepson/netstatus/errors/%s",d->d_name);
          read=fopen(szBuf2,"r");          
     }
}
basicly i want to be able to open and print each file returned in the directory listing.
ASKER CERTIFIED SOLUTION
Avatar of sunnycoder
sunnycoder
Flag of India image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
thanks. Just one question, why do you have to use fgets to get the contents on the file
fopen simply opens the file and gives you the handle for the open file ... next you need to use that handle to read from the file ... that is exactly what fgets does ...

reads a line from the open file