c++ - Enter all subfolders - Recursive -
how can write program enters of folder' subfolders?
wrote code, not enter subfolders.
void main(int argc, char *argv[]) { char* dirpath = argv[1]; struct stat statbuf; dir *dir; struct dirent *ent; size_t arglen = strlen(argv[1]); if ((dir = opendir (dirpath)) != null) { while ((ent = readdir (dir)) != null) { printf(ent->d_name, "%s\n"); } closedir (dir); } else { perror ("problem"); } }
i tried using stat() function recursively.
http://www.lemoda.net/c/recursive-directory/
#include <stdlib.h> #include <stdio.h> #include <sys/types.h> #include <string.h> #include <errno.h> /* "readdir" etc. defined here. */ #include <dirent.h> /* limits.h defines "path_max". */ #include <limits.h> /* list files in "dir_name". */ static void list_dir (const char * dir_name) { dir * d; /* open directory specified "dir_name". */ d = opendir (dir_name); /* check opened. */ if (! d) { fprintf (stderr, "cannot open directory '%s': %s\n", dir_name, strerror (errno)); exit (exit_failure); } while (1) { struct dirent * entry; const char * d_name; /* "readdir" gets subsequent entries "d". */ entry = readdir (d); if (! entry) { /* there no more entries in directory, break out of while loop. */ break; } d_name = entry->d_name; /* print name of file , directory. */ printf ("%s/%s\n", dir_name, d_name); #if 0 /* if don't want print directories, use following line: */ if (! (entry->d_type & dt_dir)) { printf ("%s/%s\n", dir_name, d_name); } #endif /* 0 */ if (entry->d_type & dt_dir) { /* check directory not "d" or d's parent. */ if (strcmp (d_name, "..") != 0 && strcmp (d_name, ".") != 0) { int path_length; char path[path_max]; path_length = snprintf (path, path_max, "%s/%s", dir_name, d_name); printf ("%s\n", path); if (path_length >= path_max) { fprintf (stderr, "path length has got long.\n"); exit (exit_failure); } /* recursively call "list_dir" new path. */ list_dir (path); } } } /* after going through entries, close directory. */ if (closedir (d)) { fprintf (stderr, "could not close '%s': %s\n", dir_name, strerror (errno)); exit (exit_failure); } } int main () { list_dir ("/usr/share/games"); return 0; }
Comments
Post a Comment