/***************************************************************************** * C Program illustrating how to handle directories * * Written by: Abhijit Das * * Last updated: October 15, 2008 * *****************************************************************************/ #include #include #include #include #include int main (int argc, char *argv[]) { char dname[1024]; /* string to store the name of a directory */ DIR *dp; /* directory pointer */ struct dirent *dep; /* pointer to a directory entry */ if (argc == 1) { /* Ask the user to enter a directory name */ printf("Enter the absolute name of a directory: "); scanf("%s", dname); } else { /* Directory name supplied as a command-line argument */ strcpy(dname,argv[1]); } dp = (DIR *)opendir(dname); /* open directory */ if (dp == NULL) { fprintf(stderr, "Error: Unable to open directory...\n"); exit(1); } printf("sizeof(struct dirent) = %d\n", sizeof(struct dirent)); while (1) { dep = readdir(dp); /* read next directory entry */ if (dep == NULL) break; /* no further files in the directory */ printf("%32s ", dep->d_name); /* print the name of the file */ switch (dep->d_type) { /* print the type of the file */ case DT_BLK: printf("[block device]\n"); break; case DT_CHR: printf("[character device]\n"); break; case DT_DIR: printf("[directory]\n"); break; case DT_FIFO: printf("[named pipe]\n"); break; case DT_LNK: printf("[symbolic link]\n"); break; case DT_REG: printf("[regular file]\n"); break; case DT_SOCK: printf("[socket]\n"); break; default: printf("[unknown]\n"); } } closedir(dp); /* close the open directory handle */ exit(0); }