Link to home
Start Free TrialLog in
Avatar of akiskal
akiskal

asked on

NEED HELP READING DIRECTORY CONTENTS RECURSIVELY

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 !!!
Avatar of ravenscr98
ravenscr98

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.
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.
SOLUTION
Avatar of Karl Heinz Kremer
Karl Heinz Kremer
Flag of United States of America 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
ASKER CERTIFIED SOLUTION
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
Avatar of akiskal

ASKER

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!
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.