Skip to content

Instantly share code, notes, and snippets.

@spl
Last active January 10, 2017 14:43
Show Gist options
  • Save spl/885b0e27335b30f29dd469b55e34b720 to your computer and use it in GitHub Desktop.
Save spl/885b0e27335b30f29dd469b55e34b720 to your computer and use it in GitHub Desktop.
Print readdir() and stat() info for each directory argument
/* For each argument, this program prints each file name in that directory plus
* the file type. Type 0 is unknown.
*/
#include <stdio.h>
#include <stdlib.h>
#include <sys/dir.h>
#include <sys/stat.h>
#include <unistd.h>
void print_readdir(char * const dir_name) {
DIR *dir = opendir(dir_name);
if (dir == NULL) {
fprintf(stderr, "Can't open directory: %s\n", dir_name);
return;
}
struct dirent *dir_info;
while ((dir_info = readdir(dir)) != NULL) {
// First, print the readdir() file type.
printf("%s: readdir_d_type=%d", dir_info->d_name, dir_info->d_type);
// Second, for comparison, print some stat() file types.
struct stat stat_info;
if (stat(dir_info->d_name, &stat_info) != -1) {
printf(" stat_is_reg=%d stat_is_dir=%d", S_ISREG(stat_info.st_mode), S_ISDIR(stat_info.st_mode));
}
printf("\n");
}
closedir(dir);
}
int main(int argc, char * const argv[]) {
// If there are no arguments, use the $PWD.
if (argc <= 1) {
print_readdir(".");
return 0;
}
// If there are arguments, print the readdir info for each argument, assuming
// it is a directory.
for (int i = 1; i < argc; i++) {
print_readdir(argv[i]);
if (i + 1 < argc) {
printf("\n");
}
}
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment