What is the proper way to do recursion

J

jackassplus

I am trying to read files in subdirectories.
I have questions:
1- What would cause (NOENT) for every file that is not int he
directory that the program is called from? (a problem with stat?)

Q:\>fopen_test .
../DJGPP
copying: No such file or directory (ENOENT)
copying.dj: No such file or directory (ENOENT)
copying.lib: No such file or directory (ENOENT)
djgpp.bat: No such file or directory (ENOENT)
djgpp.env: No such file or directory (ENOENT)
....

2- Why would Valgrind say I have 1 block left not freed when the
read_me() is called from itself, but not when that line is commented
out ?

Compiled with "gcc -Wall -o fopen_test.exe fopen_test.c"
no errors

Code:
#include <stdlib.h>
#include <sys/types.h>
#include <stdio.h>
#include <string.h>
#include <sys/stat.h>
#include <errno.h>
#include <dirent.h>
#include <unistd.h>

#define BUFSIZE 1024

char buf[BUFSIZE];
FILE *Fp;
DIR *d;
struct dirent *dir;
char *ps;
char dir_array[5][BUFSIZE]={{'\0'}} ;

int isdir (char *name){
struct stat st;

if (stat (name, &st)){
perror (name);
return 0;
}
return S_ISDIR (st.st_mode);
}


void read_me( char* path ) {
char cat_path[BUFSIZE]="";
char cur_file[BUFSIZE] = {'\0'};
if((d = opendir(path)) != NULL) {
while( ( dir = readdir( d ) ) != NULL ) {
if (strlen(cat_path) > 1) {
strcpy(cur_file,cat_path);
}else{
strcpy(cur_file,path);
strcat(cur_file, "/");
strcat(cur_file, dir->d_name);
}

if (isdir(dir->d_name)){
//Populate an array of folder paths

//dive into the directory
if((strcmp((char*)dir->d_name, "." ) != 0 && strcmp((char*)dir-
d_name, ".." ) != 0)) {
strcpy( cat_path, path );
strcat( cat_path, "/" );
strcat( cat_path, (char*)dir->d_name );
printf("%s\n",cat_path);
read_me(cat_path); //recursion
}
}else{
if((strcmp((char*)cur_file, "." ) != 0
&& strcmp( (char*)cur_file, ".." ) != 0)){

Fp = fopen(cur_file, "r");
//printf(dir->d_name);
fclose(Fp);
}
}
}
}else{
printf("opendir(%s) failed\n", path);
closedir(d);
}
}
int main(int argc, char **argv){
if (argc>1){
read_me(argv[1]);
} else {
printf("Need args, man!");
}
return 0;
}
 
A

Antoninus Twink

1- What would cause (NOENT) for every file that is not int he
directory that the program is called from? (a problem with stat?) [snip]
if (isdir(dir->d_name)){

You want to pass the cur_file that you've just carefully constructed to
isdir(), not dir->d_name.
2- Why would Valgrind say I have 1 block left not freed when the
read_me() is called from itself, but not when that line is commented
out ?

Probably because you fail to call closedir() on d.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,962
Messages
2,570,134
Members
46,690
Latest member
MacGyver

Latest Threads

Top