Use C ++ to implement the ls function of shell in Linux.

Source: Internet
Author: User
Tags lstat

Use C ++ to implement the ls function of shell in Linux.

Output the file name in the current directory

Ls function:

Method 1:

#include <iostream>#include <algorithm>#include <stdio.h>#include <stdlib.h>#include <dirent.h>#include <sys/types.h>#include <string.h>#include <string>using namespace std;bool cmp( string s1,string s2){  return s1<s2;}int main(){  DIR *dir;  char s[100];  string data[100];  int tot=0;  struct dirent *rent;  dir =opendir(".");  while(rent=readdir(dir))  {      strcpy(s,rent->d_name);      if(s[0]!='.'){       data[tot]=s;      tot++;      }  }  sort(data,data+tot,cmp);  for(int i=0;i<tot;i++)   cout<<data[i]<<"  ";  puts("");  closedir(dir);  return 0;}

 

Method 2:

# Include <sys/types. h> # include <sys/stat. h> # include <unistd. h> # include <stdio. h> # include <string. h> # include <errno. h> # include <pwd. h> # include <grp. h> # include <time. h> # include <dirent. h> int do_ls (char * dir, char * filename, int lflag) {int n; struct stat buf; char out [100]; struct passwd * pw; struct group * gr; struct tm * t; if (lflag = 0) // if the l parameter is not included, the file/directory name {printf ("% s \ t", filename) is displayed directly ); return 0;} if (l Stat (dir, & buf) <0) {fprintf (stderr, "stat error: % s \ n", strerror (errno); return-1;} switch (buf. st_mode & S_IFMT) // obtain the attributes of a string: common file-, Directory d, character Device c, block Device B, MPs, connection file l, socket File s {case S_IFREG: printf ("-"); break; case S_IFDIR: printf ("d"); break; case S_IFCHR: printf ("c"); break; case S_IFBLK: printf ("B"); break; case s_ifififo: printf ("p"); break; case S_IFLNK: printf ("l"); break; case S_IFSOCK: printf ("s"); br Eak ;}for (n = 8; n> = 0; n --) // print the read/write attributes of the file: read r, write w, execute x, no permission-{if (buf. st_mode & (1 <n) {switch (n % 3) {case 2: printf ("r"); break; case 1: printf ("w "); break; case 0: printf ("x"); break; default: break; }}else {printf ("-") ;}} printf ("% d", buf. st_nlink); // number of hard links. This link is not a link of the other. It refers to the number of (including) directories. The file is 1 and the Directory starts from 2, add the number of directories in the directory (no recursion, only one layer) pw = getpwuid (buf. st_uid); // username printf ("% s", pw-> pw_name); gr = getgrgid (buf. st_gid ); // Group name printf ("% s", gr-> gr_name); printf ("% ld", buf. st_size); // The total size of the byte t = localtime (& buf. st_atime); // The last access time printf ("% d-% d: % d", t-> tm_year + 1900, t-> tm_mon + 1, t-> tm_mday, t-> tm_hour, t-> tm_min); printf ("% s", filename); if (S_ISLNK (buf. st_mode) // determines whether it is a link. returns true {printf ("->"); if (readlink (filename, out, 100) =-1) {// printf ("readlink error \ n");} printf ("% s", out);} printf ("\ n"); return 0;} Int ls_prepare (char * w, int aflag, int lflag) // The preparation of ls {struct stat buf; // man lstat can see the structure of char name [100]; DIR * dir; // similar to the fd descriptor struct dirent * pdr for opening the file; // man readdir can see this structure if (lstat (w, & buf) <0) // obtain the file/directory attribute and assign it to buf. This function is the same as lstat, but when w is a link, it refers to itself, and there is no file {fprintf (stderr, "stat error: % s \ n", strerror (errno); return-1;} if (S_ISDIR (buf. st_mode) // determines whether it is a directory, returns true {dir = opendir (w); // opens the directory while (pdr = readdi R (dir ))! = NULL) // read/traverse the directory {if (aflag = 0) // if the parameter is not included. all files/directories starting with {if (pdr-> d_name [0] = '. ') continue; memset (name, 0,100); strcpy (name, w); // copy strcat (name, "/"); // append strcat (name, pdr-> d_name); do_ls (name, pdr-> d_name, lflag);} else // All {memset (name, 0,100); strcpy (name, w); strcat (name, "/"); strcat (name, pdr-> d_name); do_ls (name, pdr-> d_name, lflag );}} closedir (dir);} else // indicates the file. {do_ls (w, w, lflag) is displayed directly );} Return 0;} int main (int argc, char ** argv) {int aflag = 0; int lflag = 0; char c; int I; while (c = getopt (argc, argv, "al "))! =-1) // parse the command line parameter, that is, the string following-/-- matches the given string. If there are unresolved letters, the return letter or question mark (depending on the 3rd parameters) is returned ), otherwise, return-1 {switch (c) // here only match a (all) and l (list), that is, only parameters a and l {case 'a' are supported ': aflag = 1; break; case 'l': lflag = 1; break; default: break;} if (argc = optind) {ls_prepare (". /", aflag, lflag);} else {for (I = optind; I <argc; I ++) // all directories are uploaded to ls_prepare (argv [I], aflag, lflag);} printf ("\ n"); return 0 ;}

 

Ls-l function:

#include <stdio.h>#include <sys/types.h>#include <dirent.h>#include <sys/stat.h>#include <pwd.h>#include <grp.h>void show_file_info(char* filename, struct stat* info_p) { char* uid_to_name(), *ctime(), *gid_to_name(), *filemode(); void mode_to_letters(); char modestr[11]; mode_to_letters(info_p->st_mode, modestr); printf("%s", modestr); printf(" %4d", (int) info_p->st_nlink); printf(" %-8s", uid_to_name(info_p->st_uid)); printf(" %-8s", gid_to_name(info_p->st_gid)); printf(" %8ld", (long) info_p->st_size); printf(" %.12s", 4 + ctime(&info_p->st_mtime)); printf(" %s\n", filename);}void mode_to_letters(int mode, char str[]) { strcpy(str, "----------"); if (S_ISDIR(mode)) {  str[0] = 'd'; } if (S_ISCHR(mode)) {  str[0] = 'c'; } if (S_ISBLK(mode)) {  str[0] = 'b'; } if ((mode & S_IRUSR)) {  str[1] = 'r'; } if ((mode & S_IWUSR)) {  str[2] = 'w'; } if ((mode & S_IXUSR)) {  str[3] = 'x'; } if ((mode & S_IRGRP)) {  str[4] = 'r'; } if ((mode & S_IWGRP)) {  str[5] = 'w'; } if ((mode & S_IXGRP)) {  str[6] = 'x'; } if ((mode & S_IROTH)) {  str[7] = 'r'; } if ((mode & S_IWOTH)) {  str[8] = 'w'; } if ((mode & S_IXOTH)) {  str[9] = 'x'; }}char* uid_to_name(uid_t uid){ struct passwd* getpwuid(),* pw_ptr; static char numstr[10]; if((pw_ptr = getpwuid(uid)) == NULL){  sprintf(numstr,"%d",uid);  return numstr; }else{  return pw_ptr->pw_name; }}char* gid_to_name(gid_t gid){ struct group* getgrgid(),* grp_ptr; static char numstr[10]; if(( grp_ptr = getgrgid(gid)) == NULL){  sprintf(numstr,"%d",gid);  return numstr; }else{  return grp_ptr->gr_name; }}void do_ls(char dirname[]) { DIR* dir_ptr; struct dirent* direntp; if ((dir_ptr = opendir(dirname)) == NULL) {  fprintf(stderr, "ls2: cannot open %s \n", dirname); } else {  while ((direntp = readdir(dir_ptr)) != NULL) {   dostat(direntp->d_name);  }  close(dir_ptr); }}void dostat(char* filename) { struct stat info; if (stat(filename, &info) == -1) {  perror(filename); } else {  show_file_info(filename, &info); }}int main(int ac,char* av[]){ if(ac == 1){  do_ls("."); }else{  while(--ac){   printf("%s: \n",*++av);   do_ls(*av);  } }}

  

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.