#include #include /* calloc() */ #include /* strlen(), strncpy() */ #include /* opendir() */ #include /* opendir() */ int printdir(char *path, char *prefix) { DIR *dp = opendir(path); if(dp != NULL) { struct dirent *file; while(file = readdir(dp)) { /* exclude current and parent entries */ if(strcmp(file->d_name,".") != 0 && strcmp(file->d_name,"..") != 0) { if(file->d_type != DT_DIR) { printf("%s%s\n", prefix, file->d_name); } else { char *newpath = NULL; char *newprefix = NULL; asprintf(&newpath, "%s%s/", path, file->d_name); asprintf(&newprefix, "%s%s/", prefix, file->d_name); printf("%s\n", newprefix); printdir(newpath, newprefix); free(newpath); free(newprefix); } } } closedir(dp); return 0; } else { return 1; } } int main(int argc, char *argv[]) { char *path; /* open the dir specified on the command line- first * ensure we have a trailing slash */ if(argv[1]) { int len = strlen(argv[1]); if(argv[1][len-1] != '/') { len += 1; } path = calloc(len + 1, sizeof(char)); strncpy(path, argv[1], len); path[len-1] = '/'; printdir(path, ""); free(path); return 0; } return 1; }