Working on a modified/simpler version of Unix 'find' utility and as I'm printing out the files, my format is off.
Running:
./a.out mydir -print
The output should be similar to find, the following:
mydir
mydir/innerDir
mydir/innerDir/innerFile
mydir/testFile
However, my output is the following:
mydir/innerDir
innerFile/testFile
This is the function that I have that traverses the directory contents:
void printdir(char *dir, int depth) {
DIR *dp;
struct dirent *entry;
struct stat statbuf;
int spaces = depth * 4;
char *path;
if((dp = opendir(dir)) == NULL) {
fprintf(stderr, "Error! Unable to open: %s\n", dir);
exit(EXIT_FAILURE);
}
chdir(dir);
while((entry = readdir(dp)) != NULL) {
lstat(entry->d_name, & statbuf);
if(S_ISDIR(statbuf.st_mode)) {
if(strcasecmp(".", entry->d_name) == 0 ||
strcasecmp("..", entry->d_name) == 0)
continue;
path = malloc(strlen(dir) + strlen(entry->d_name) + 2);
strcpy(path, dir);
strcat(path, "/");
strcat(path, entry->d_name);
// printf("%*s|-- %s/\n", spaces, "", entry->d_name);
printf("%s\n", path);
printdir(entry->d_name, depth + 1);
}
else
// printf("%*s|-- %s\n", spaces, "", entry->d_name);
printf("%s/", entry->d_name);
}
chdir("..");
closedir(dp);
}
The commented lines above prints out similar output to Unix 'tree' utility. Any help on how to modify my printing to obtain 'find' output I listed above. Thank you!
Just a bad parameter at the recursion call, send the full path:
printdir(path, depth + 1);
and then for non directory entries, also print the full path:
printf("%s/%s\n", dir, entry->d_name);
----EDIT----
Remove all the calls to chdir
as you generated the full path.
----EDIT-2----
lstat
not called on the correct path, modify to:
while((entry = readdir(dp)) != NULL) {
path = malloc(strlen(dir) + strlen(entry->d_name) + 2);
strcpy(path, dir);
strcat(path, "/");
strcat(path, entry->d_name);
lstat(path, & statbuf);