Solved

NEED HELP READING DIRECTORY CONTENTS RECURSIVELY

Posted on 2004-04-13
7
570 Views
Last Modified: 2010-05-18
Hi everyone!

This is my problem:
I'm trying to read the contents of a directory recursively and below is my code so far... I'm sure I have a lot of mistakes but could anyone help me? When I run this program I get Segmentation fault ! What should I do???


DIR* directory;
struct dirent* pdirent;
struct stat  Stat;

void perform( char* A )
{

        if(stat(A , &Stat) < 0)
        {
                printf("Error !!!!");
                return;
        }

        directory = opendir(A);
        while( (pdirent = readdir(directory)) != NULL)
        {

                if((pdirent -> d_name != ".") && (pdirent->d_name != ".."))
                {
                        printf("%s \n" , pdirent -> d_name);

                        if(S_ISDIR(Stat.st_mode))
                        {
                                perform(pdirent-> d_name);

                        }
                 }
        }

        closedir(directory);

}


In main I call perform( argv[1] )



I'd appreciate any help !!!
0
Comment
Question by:akiskal
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
7 Comments
 
LVL 1

Expert Comment

by:ravenscr98
ID: 10818318
First, make your variables local to the function.  Each directory needs its own DIR* pointer, otherwise when you backtrack from the recursive call the variable directory has changed its value.

Also, when you test to see if the current file name is a directory in order to recursively descend, you are testing Stat for the current directory you are in, not for the file name you have just read.

Look at those two issues.  If you still get a seg fault, figure out where it is and I'm sure one of the experts here can help.
0
 
LVL 44

Expert Comment

by:Karl Heinz Kremer
ID: 10819091
THere are a few more problems: You cannot compare strings with != - you need to use strcmp(), also, when you call perform() recursively, you are only passing in the subdirectory, and not the whole directory (consisting of the base dirctory (A) plus the subdir.
0
 
LVL 44

Assisted Solution

by:Karl Heinz Kremer
Karl Heinz Kremer earned 125 total points
ID: 10819181
Try this:

#include <sys/stat.h>
#include <sys/types.h>
#include <stdio.h>
#include <dirent.h>
#include <linux/limits.h>

void
perform (char *A)
{
  DIR *directory;
  struct dirent *pdirent;
  struct stat Stat;
  directory = opendir (A);
  while ((pdirent = readdir (directory)) != NULL)
    {
      if (strcmp (pdirent->d_name, ".") && strcmp (pdirent->d_name, ".."))
        {
          printf ("%s \n", pdirent->d_name);
          char newpath[PATH_MAX];
          sprintf (newpath, "%s/%s", A, pdirent->d_name);
          if (stat (newpath, &Stat) < 0)
            {
              printf ("Error !!!!\n");
              return;
            }
          if (S_ISDIR (Stat.st_mode))
            {
              perform (newpath);
            }
        }
    }
  closedir (directory);
}

int
main (int argc, char *argv[])
{
  perform (argv[1]);
}

But keep in mind that I'm not doing any error checking. As soon as you try to e.g. traverse into a directory that you cannot read, it will segfault. But other than that it does work correctly. There was another problem with the call to stat(): You only called it for the directory, but not for any of the directory entries you read.
0
Learn by Doing. Anytime. Anywhere.

Do you like to learn by doing?
Our labs and exercises give you the chance to do just that: Learn by performing actions on real environments.

Hands-on, scenario-based labs give you experience on real environments provided by us so you don't have to worry about breaking anything.

 
LVL 9

Accepted Solution

by:
Alf666 earned 175 total points
ID: 10819253
The following will work. But you have a lot to learn. I suggest you examine line by line...

#include <sys/types.h>
#include <dirent.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <stdio.h>

void perform( char* A )
{
  DIR *directory;
  struct dirent *pdirent;
  struct stat Stat;
  struct stat fileStat ;
  char fileName[FILENAME_MAX] ;

  if(stat(A , &Stat) < 0) {
    perror(A);
    return;
  }

  directory = opendir(A);

  while ((pdirent = readdir(directory)) != NULL) {

    if (strncmp(pdirent->d_name, ".", 1)
      && strncmp(pdirent->d_name, "..", 2)) {

      if (snprintf(fileName, FILENAME_MAX, "%s/%s", A, pdirent->d_name)
        >= FILENAME_MAX) {
      fprintf(stderr, "File name too long : %s", fileName) ;
      return ;
      }

      if(stat(fileName , &fileStat) < 0) {
      perror(fileName);
      continue ;
      }
      printf("%s \n" , fileName);
     
      if(S_ISDIR(fileStat.st_mode)) {
      printf("doing : %s\n" , fileName);
      perform(fileName);
      }

    }
  }
  closedir(directory);
}


main(int argc, char **argv) {

  perform( argv[1] ) ;
}
0
 

Author Comment

by:akiskal
ID: 10822364
Thanks very much guys I really appreciate your help!!!!  

khkremer I made a mistake when I accepted tha last answer and I didn't give you any points!!! I'm really sorry but I really thank you for your help!

Everything worked fine with Alf666 's code and now I can go on with my work! Thanks again guys!
0
 
LVL 44

Expert Comment

by:Karl Heinz Kremer
ID: 10822386
You can post a request in the Support area (see the link at the top of the page) and have them re-open this question (happens all the time). This will allow you to accept the correct answer(s) again.  
0

Featured Post

On Demand Webinar: Networking for the Cloud Era

Did you know SD-WANs can improve network connectivity? Check out this webinar to learn how an SD-WAN simplified, one-click tool can help you migrate and manage data in the cloud.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Have you ever been frustrated by having to click seven times in order to retrieve a small bit of information from the web, always the same seven clicks, scrolling down and down until you reach your target? When you know the benefits of the command l…
The purpose of this article is to fix the unknown display problem in Linux Mint operating system. After installing the OS if you see Display monitor is not recognized then we can install "MESA" utilities to fix this problem or we can install additio…
There's a multitude of different network monitoring solutions out there, and you're probably wondering what makes NetCrunch so special. It's completely agentless, but does let you create an agent, if you desire. It offers powerful scalability …
In this brief tutorial Pawel from AdRem Software explains how you can quickly find out which services are running on your network, or what are the IP addresses of servers responsible for each service. Software used is freeware NetCrunch Tools (https…

628 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question