This basically involves calling appropriate functions.
int chdir(char path) - changes directory to specified path string.
Example: C emulation of UNIX's cd command:
char getwd(char path) - get the full pathname of the current working directory. path is a pointer to a string where the pathname will be returned. getwd returns a pointer to the string or NULL if an error occurs.
scandir(char dirname, struct direct namelist, int (*select)(), int (compar)()) - reads the directory dirname and builds an array of pointers to directory entries or -1 for an error. namelist is a pointer to an array of structure pointers.
(*select))() is a pointer to a function which is called with a pointer to a directory entry (defined in <sys/types> and should return a non zero value if the directory entry should be included in the array. If this pointer is NULL, then all the directory entries will be included.
The last argument is a pointer to a routine which is passed to qsort (see man qsort) - a built in function which sorts the completed array. If this pointer is NULL, the array is not sorted.
alphasort(struct direct d1, d2) - alphasort() is a built in routine which will sort the array alphabetically.
Example - a simple C version of UNIX ls utility
scandir returns the current directory (.) and the directory above this (..) as well as all files so we need to check for these and return FALSE so that they are not included in our list.
Note: scandir and alphasort have definitions in sys/types.h and sys/dir.h. MAXPATHLEN and getwd definitions in sys/param.h
We can go further than this and search for specific files: Let's write a modified file_select() that only scans for files with a .c, .o or .h suffix:
NOTE: rindex() is a string handling function that returns a pointer to the last occurrence of character c in string s, or a NULL pointer if c does not occur in the string. (index() is similar function but assigns a pointer to 1st occurrence.)