I writing this programe to recursively search and print out all files and directories. If no argument is passed it, it will start with the root. If an argument is given, it will start with the directory corresponding to the argument. It seems to work fine the first way through, but the S_ISDIR or stat functions are not working when a directory is found....or if an argument is present. Anybody have any ideas?
#include <sys/types.h> /* for opendir(), readdir(), closedir() */
#include <dirent.h>
#include <unistd.h>
#include <sys/stat.h> /* for stat() */
#include <string.h>
#include <stdio.h>
#define N 7
long power(int, int);
void prn_heading(void);
void listdir(int, char*);
int main(int argc, char *argv[])
{
int level = 0;
printf("\n::::: DIRECTORY LISTING :::::\n\n");
if ( argc == 1)
{
char *d = ".";
listdir(level, d);
}
if( argc > 2)
{
fprintf( stderr, "Usage: %s [dirname]\n", argv[0]);
return 1;
}
if( argc > 1)
{
char *d = argv[1];
listdir(level, d);
}
return 0;
}
void listdir(int level, char *d)
{
DIR *dirfp;
struct dirent *de;
struct stat stat_buf;
int is_dir;
char *name;
char *newd;
name = getcwd(NULL,64);
name = strcat( name,"/");
name = strcat( name,d);
/* ##########################
######## */
/* ####### Opens Directory ######## */
/* ##########################
######## */
if( (dirfp = opendir( name)) == NULL)
{
return;
}
/* ##########################
##########
##########
##########
# */
while( (de = readdir( dirfp)) != NULL)
{
is_dir = 0;
/* ##########################
##########
##########
##########
# */
/* #### Removes the . and .. directories from the list ##### */
/* ##########################
##########
##########
##########
# */
if (strcmp (de->d_name, ".") != 0 && strcmp(de->d_name, "..") != 0)
{
stat( de->d_name, &stat_buf);
is_dir = S_ISDIR( stat_buf.st_mode);
/* printf("is_dir = %d\n", is_dir); */
if (level == 0)
{
printf( "%s%s\n", de->d_name, is_dir ? " (d)" : "");
}
if (level == 1)
{
printf( " %s%s\n", de->d_name, is_dir ? " (d)" : "");
}
if (level == 2)
{
printf( " %s%s\n", de->d_name, is_dir ? " (d)" : "");
}
if (level == 4)
{
printf( " %s%s\n", de->d_name, is_dir ? " (d)" : "");
}
newd = de->d_name;
listdir(level+1, newd);
}
}
closedir( dirfp);
return;
}