1 ls -R 2 #include <sys/stat.h> 3 #include <dirent.h> 4 #include <fcntl.h> 5 #include <stdbool.h> 6 #include <stdio.h> 7 8 9 int do_ls(const char *dir) 10 { 11 char dir_name[128]; 12 DIR *dirp; 13 struct dirent *dp; 14 struct stat dir_stat; 15 16 if ( 0 != access(dir, F_OK) ) 17 { 18 return 0; 19 } 20 21 if ( 0 > stat(dir, &dir_stat) ) 22 { 23 perror("get directory stat error"); 24 return -1; 25 } 26 27 28 if ( S_ISDIR(dir_stat.st_mode) ) 29 { 30 dirp = opendir(dir); 31 printf("%s: ",dir); 32 int count = 0; 33 while ( (dp=readdir(dirp)) != NULL ) 34 { 35 36 ++count; 37 if ( (0 == strcmp(".", dp->d_name)) || (0 == strcmp("..", dp->d_name)) ) { 38 continue; 39 } 40 printf("%s ",dp->d_name); 41 if(5 == count) 42 { 43 printf(" "); 44 count = 0; 45 } 46 47 } 48 printf(" --- "); 49 rewinddir(dirp); 50 51 while ( (dp=readdir(dirp)) != NULL ) 52 { 53 if ( (0 == strcmp(".", dp->d_name)) || (0 == strcmp("..", dp->d_name)) ) { 54 continue; 55 } 56 57 char buf[100] = {}; 58 sprintf(buf,"%s/%s",dir,dp->d_name); 59 do_ls(buf); 60 61 } 62 } 63 64 } 65 int main() 66 { 67 do_ls("."); 68 }
rm -r
1 #include <stdio.h> 2 #include <stdlib.h> 3 #include <sys/types.h> 4 #include <sys/stat.h> 5 #include <unistd.h> 6 #include <fcntl.h> 7 #include <dirent.h> 8 #include <libgen.h> 9 #include <string.h> 10 void rmr(char* path) 11 { 12 DIR* dir = opendir(path); 13 if(dir == NULL) 14 perror("opendir"),exit(-1); 15 struct dirent* ent; 16 char buf[256]; 17 while((ent=readdir(dir))) 18 { 19 if(ent->d_type == 4) 20 { 21 if(strcmp(ent->d_name,".")==0||strcmp(ent->d_name,"..")==0) 22 continue; 23 sprintf(buf,"%s/%s",path,ent->d_name); 24 25 rmr(buf); 26 27 } 28 if(ent->d_type == 8) 29 { 30 sprintf(buf,"%s/%s",path,ent->d_name); 31 if(remove(buf)!=0) perror("remove"),exit(-1); 32 } 33 } 34 if(rmdir(path)!=0) perror("rmdir"),exit(-1); 35 } 36 int main(int argc,char* argv[]) 37 { 38 if(argc != 2) 39 { 40 printf("Usage:%s directory name",basename(argv[0])); 41 exit(-1); 42 } 43 44 rmr(argv[1]); 45 printf("rm -r %s success. ",argv[1]); 46 return 0; 47 }
1 ls -l 2 #include <stdio.h> 3 #include <sys/types.h> 4 #include <dirent.h> 5 #include <sys/stat.h> 6 #include <pwd.h> 7 #include <grp.h> 8 #include <unistd.h> 9 10 void show_file_info(char* filename, struct stat* info_p) 11 { 12 char* uid_to_name(), *ctime(), *gid_to_name(), *filemode(); 13 void mode_to_letters(); 14 char modestr[11]; 15 16 mode_to_letters(info_p->st_mode, modestr); 17 18 printf("%s", modestr); 19 printf(" %4d", (int) info_p->st_nlink); 20 printf(" %-8s", uid_to_name(info_p->st_uid)); 21 printf(" %-8s", gid_to_name(info_p->st_gid)); 22 printf(" %8ld", (long) info_p->st_size); 23 printf(" %.12s", 4 + ctime(&info_p->st_mtime)); 24 struct passwd *curr; 25 curr = getpwuid(getuid()); 26 27 if(curr->pw_gid == info_p->st_gid && info_p->st_mode & S_IXGRP ) 28 { 29 printf("