/* readdir.c */ #include #include #include #include #include #include #include #include #include int main( int argc, char **argv) { DIR *procdir; struct dirent *de; /* make sure user provided a directory name */ if (argv < 2) { fprintf(stderr, "Usage is readdir dir-name \n"); exit(1); } /* The opendir function is used to open a directory for */ /* reading by readdir() */ procdir = opendir(argv[1]); /* After any system call it is important to verify that */ /* it actually worked rather than blindly pressing on */ /* assuming that it did. If it failed the perror() */ /* function will convert the code stored in "errno" */ /* to a moderately informative message.. */ /* For example, try readdir /home/westall/acad/cs422 */ /* or readdir /home/westall/blah/blah/blah */ if (procdir == 0) { perror("open failed"); exit(1); } /* The readdir() function returns a pointer to the next */ /* struct dirent in the directory or NULL at end */ /* The d_name element holds the file or subdir name */ /* The %-10s format code says to left justify the string */ /* in a field of width 10. */ while ((de = readdir(procdir)) != 0) printf("%-10s \n", de->d_name); }