The C language implementation of the LS command under Linux (supports-R-parameters):
#include <stdio.h> #include <sys/types.h> #include <dirent.h> #include <sys/stat.h> #include <pwd.h> #include <grp.h> #include <string.h>void Do_ls (char *), void Do_stat (char *,char *); void Show_ File_info (char *,struct stat *,char *), void mode_to_letters (int, char []), char * uid_to_name (uid_t); char * Gid_to_name (GI d_t); int recursive = 0;int main (int Argc,char * argv[]) {int i;for (i = 1;i < argc;i++) {if (strcmp (Argv[i], "-r") = = 0) {Rec ursive = 1;break;}} if (argc = = 1 && recursive = = 0) Do_ls ("."); else if (argc = = 2 && recursive = = 1) Do_ls ("."); Else{int index = 1;while (argc > 1) {if (strcmp (Argv[index], "-r")! = 0) Do_ls (Argv[index]); index++;argc--;}} return 0;} void Do_ls (char * path) {dir * dir;struct dirent * direntp;if ((dir = opendir (path)) = NULL) {while (DIRENTP = Readdir (DIR)) ! = NULL) {char absolute_pathname[255];strcpy (absolute_pathname,path); Strcat (Absolute_pathname, "/"); Strcat ( Absolute_pathname,direntp->d_name);p rintf ("%s\n", AbsoluTe_pathname);d O_stat (absolute_pathname,direntp->d_name);} Closedir (dir);} elsefprintf (stderr, "can ' t open%s", path); void Do_stat (char * absolute_filename,char * filename) {struct stat s;if (lstat (absolute_filename,&s) = =-1) perror ( Absolute_filename); Elseshow_file_info (absolute_filename,&s,filename);} void Show_file_info (char * absolute_filename,struct stat * Info,char * filename) {char mode[11];mode_to_letters (info- >st_mode,mode);p rintf ("%s", mode);p rintf ("%d", Info->st_nlink);p rintf ("%s", Uid_to_name (Info->st_uid)); printf ("%s", Gid_to_name (Info->st_gid));p rintf ("%d", info->st_size);p rintf ("%.12s", 4+ctime (&info-> st_mtime));p rintf ("\ n"), if (recursive = = 1) {if (S_isdir (Info->st_mode) && strcmp (filename, ".")! = 0 && strcmp (filename, "...")! = 0) Do_ls (absolute_filename);}} void mode_to_letters (int mode,char * c_mode) {strcpy (C_mode, "----------"), if (S_isdir (mode)) c_mode[0] = ' d '; if (S_ISCHR (mode)) C_mode[0] = ' C '; if (s_isblk (mode)) c_mode[0] = ' B '; if (moDe & s_irusr) c_mode[1] = ' R ', if (Mode & S_IWUSR) c_mode[2] = ' W '; if (mode & S_IXUSR) c_mode[3] = ' x '; if (Mode & S_IRGRP) C_mode[4] = ' R '; if (Mode & S_IWGRP) c_mode[5] = ' W '; if (Mode & S_IXGRP) c_mode[6] = ' x '; if (mode & S_iroth) c_mode[7] = ' R '; if (Mode & S_iwoth) c_mode[8] = ' W '; if (Mode & S_ixoth) c_mode[9] = ' x ', if (Mode & s_isuid) c_mode[3] = ' S '; if (mode & S_isgid) c_mode[6 ] = ' s '; if (mode & s_isvtx) c_mode[9] = ' s ';} char * uid_to_name (uid_t uid) {struct passwd * passwd_pointer;passwd_pointer = Getpwuid (UID); return passwd_pointer-> Pw_name;} char * gid_to_name (gid_t gid) {struct Group * group_pointer;static Char numstr[10];if ((Group_pointer = Getgrgid (gid)) = = NU LL) {sprintf (Numstr, "%d", GID); return numstr;} return group_pointer->gr_name;}
Write your own shell command of LS