Useful if you need your program to scan a subdirectory. A useful enhancement to this code would be to report an error if more than one command-line parameter is entered.
/* CExplore The DIRENT library provides handy functions */
/* to read (sub)directory locations on our filesystem. */
/* NOTE: dirent.h and its functions are not considered */
/* part of the 'C' standard. They are a sort of pseudo- */
/* standard, yet are generally portable. */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <dirent.h> // for the DIRENT functions
int main(int argc, char *argv[])
{
char dirspec[128];
struct dirent *entry;
DIR *dp;
if (argc == 2)
strcpy(dirspec, argv[1]);
else
strcpy(dirspec, "./");
printf("\n\n");
dp = opendir(dirspec);
if (dp == NULL) {
perror("opendir");
return(-1);
}
while ((entry = readdir(dp)) != (struct dirent *) NULL) {
printf("File %-32s = ", entry->d_name);
// the 'switch' + 'case' is akin to IF - ELSE IF - ELSE IF - ELSE IF - ELSE IF
switch(entry->d_type) {
case DT_UNKNOWN : printf("unknown type\n"); break;
case DT_REG : printf("regular file\n"); break;
case DT_DIR : printf("directory or hidden\n"); break;
case DT_FIFO : printf("a pipe or FIFO\n"); break;
case DT_SOCK : printf("a local-domain socket\n"); break;
case DT_CHR : printf("a character device\n"); break;
case DT_BLK : printf("a block device\n"); break;
case DT_LNK : printf("a symbolic link\n"); break;
}
}
closedir(dp);
printf("\n\n");
return(0);
}