闲来无事,随便写写,实现简单的ls命令:
| 1 #include <stdio.h>
| 2 #include <stdlib.h>
| 3 #include <dirent.h>
| 4 #include <string.h>
| 5
| 6 int main(int argc, char **argv)
| 7 {
| 8 DIR *pDir;
| 9 struct dirent *stDir;
| 10 int flag = 0;
| 11
| 12 if(argc > 2)
| 13 {
| 14 printf("Usage: ./ls or ./ls xxx\n");
| 15 exit(-1);
| 16 }
| 17 if(argc == 1)
| 18 {
| 19 flag = 1;
| 20 if((pDir = opendir(".")) == NULL)
| 21 {
| 22 printf("open dir error!\n");
| 23 exit(-1);
| 24 }
| 25 }
| 26
| 27 if(!flag)
| 28 {
| 29 if((pDir = opendir(argv[1])) == NULL)
| 30 {
| 31 printf("open dir error!\n");
| 32 exit(-1);
| 33 }
| 34 }
| 35
| 36 while((stDir = readdir(pDir)) != NULL)
| 37 {
| 38 if(strcmp(stDir->d_name, ".") == 0 || strcmp(stDir->d_name, "..") == 0)
| 39 continue;
| 40 printf("%s\n", stDir->d_name);
| 41 }
| 42
| 43 closedir(pDir);
| 44
| 45 return 0;
| 46 }
功能:
./ls ——列出当前目录下文件
./ls xxx——列出指定目录下文件
忽略.与..两个目录。