/* by Mark A. Sheldon, February 2005 */ #include #include #include #include #include #include /* Usage: lsdir [dirname] Prints the files in the specified directory or "." if no dirname is given. */ void lsdir(char *path) { DIR *dirp; struct dirent *entry; dirp = opendir(path); if (dirp == NULL) { fprintf(stderr, "lsdir: Cannot open %s: %s\n", path, strerror(errno)); exit(EINVAL); } /* Reset errno on each iteration to detect readdir() errors */ while ( errno = 0, (entry = readdir(dirp)) != NULL ) puts(entry->d_name); if (errno != 0) fprintf(stderr, "lsdir: Error reading %s: %s\n", path, strerror(errno)); /* Since we're already done, is there really a reason to check for failure on close? */ if (closedir(dirp) == -1) fprintf(stderr, "lsdir: Error closing %s: %s\n", path, strerror(errno)); return; } /* lsdir */ int main(int argc, char* argv[]) { char *dirname; if (argc > 2) { fprintf(stderr, "Usage: %s [dirname]\n", argv[0]); exit(EINVAL); } if (argc == 2) dirname = argv[1]; else dirname = "."; lsdir(dirname); return 0; } /* main() */