一个简单的ls命令的实现:
#include <stdio.h> #include <dirent.h> int main(int argc, char *argv[]) { DIR *dp; struct dirent *dirp; if(argc != 2) { fprintf(stderr, "usage: ls directory_name "); return -1; } if((dp = opendir(argv[1])) == NULL) { fprintf(stderr, "opendir %s error", argv[1]); return -1; } while((dirp = readdir(dp)) != NULL) { printf("%s ", dirp->d_name); } if(closedir(dp) == -1) { return -1; } return 0; }