Simple simulation implementation of LS command under Linux __linux

Source: Internet
Author: User

This is my operating system this course problem, now take out and share with you.


Welcome to discuss and communicate with me

/** * Simple implementation of LS command in linux environment * copyright©2011 Hang Studio. All rights reserved. * #include <stdio.h> #include <stdlib.h> #include <dirent.h> #include <errno.h> #include < string.h> #include <sys/ioctl.h> #include <unistd.h> #include <termios.h> #include <sys/stat.h >/* Output Group interval * * #define SPACE 2/* Get unsigned integer decimal number length * * unsigned get_unsigned_len (unsigned n) {unsigned len = 0; do{++len; n /= 10; }while (n); return Len; }/* "string" struct/typedef struct{CHAR *str;/* actual content * * Unsigned length;/* string length/}string; The number of file names in the typedef struct{UNSIGNED length;/* Collection * * Unsigned i,j;/*i is the number of rows, J is the number of columns/String *filenames; unsigned maxlen;/* Maximum filename length in file name/char **formats;/* format OUTPUT sequence * * *}FORMATINFO; /* Pre-read directory root, store formatted output information in info/void Preread (char *root, FormatInfo *info) {DIR *dir; unsigned i,j,count = 0; struct dirent *ptr; String filename; /*g is an auxiliary variable/unsigned *g = NULL based on the length of the directory entry name under the directory. unsigned width = 0; unsigned group = 0; unsigned max = 0; unsigned row = 1; Unsigned pOS = 0; struct Winsize t_size; IOCTL (Stdin_fileno, Tiocgwinsz, &t_size);//* Get the number of rows and columns of the terminal */if (info = NULL) {printf ("error! /"info/" Can not be null!/n "); Return Dir = opendir (root); if (dir = = NULL) {perror ("Fail to open dir./n"), exit (1), while (Readdir (dir)) ++count;/* the number of statistics files and directories/* Rewinddir (dir);/* rollback Read the directory's pointer/info->filenames = (String *) malloc (sizeof (String) * count); g = (unsigned *) malloc (sizeof (unsigned) * count); i = 0; /* Get file or directory name and compute its length/while (ptr = Readdir (dir)!= NULL) {filename.str = ptr->d_name;/* file or directory name * * * filename.length = strlen (Ptr->d_name); info->filenames[i++] = filename; /* To sort directory entries from small to large by directory name or filename////////////for (I=0;i<count;++i) {for (j=i;j<count;++j) {if strcmp (info-> FILENAMES[I].STR, Info->filenames[j].str) > 0) {filename = info->filenames[i]; info->filenames[i] = info- >filenames[j]; INFO-&GT;FILENAMES[J] = filename; }}/* Test the number of groups in the last list with a heuristic method/group = count;/* First assume the count list/row = 1;/* The number of rows per column is 1*/do{for (j=0,width=0;j<group++J) {for (i=0,max=0;i<row;++i) {* * * Find the longest file or directory name in each column * * pos = j*row + i; if (POS >= count) break; if (Info->filenam Es[pos].length > Max) {max = info->filenames[pos].length; g[j] = max;/* Store The maximum width of each list in the G Array/}}/* * to match the length of the longest file or directory name of each group Add * to the interval between the list also counted */width + = (max + space); /* If its total width is greater than the width of the terminal (number of columns) * Then reduce the number of grouped lists, continue to test. */if (width >= t_size.ws_col) {--group/* Here is the maximum number of rows per list that is calculated from the total quantity and list quantity * */row = (Count%group)? ( COUNT/GROUP+1):(count/group); }else{/* Otherwise, the number of estimated list ends/break;} while (1); /* Next organizes the formatted output string for each list/info->formats = (char * *) malloc (sizeof (char *) * group); Info->maxlen = 0; for (I=0;i<group;++i) {if (G[i] > Info->maxlen) Info->maxlen = g[i];/* here to find the maximum file or directory name length, later useful/g[i] + = space;/* The interval between the lists is calculated as * * j = Get_unsigned_len (G[i]) + 4; Info->formats[i] = (char *) malloc (sizeof (char) * j); sprintf (Info->formats[i], "%%-%us", g[i);/* This is the key part of the organization formatted output string/info->formats[i][j] = '/0 '; } putchar ('/n '); Info->length = count; Info->i = row;/* List Number of rows */INFO-&Gt;j = group;/* List quantity */free (g); Closedir (dir); } void My_ls (char *root) {formatinfo fi; int i,j,pos,len; char *filepath = NULL; struct stat buf; Preread (ROOT,&AMP;FI); * Pre-read directory */len = strlen (root); filepath = (char *) malloc (sizeof (char) * (strlen (root) +fi.maxlen+1)); Filepath[0] = '/0 '; strcat (Filepath,root); if (filepath[len-1]!= '/') {filepath[len++] = '/';//* Here only consider under Linux System/} for (I=0,pos=0;i<fi.i;++i) {for (J=0;J&LT;FI.J ++J) {pos = j*fi.i + i; if (pos < fi.length) {Filepath[len] = '/0 '; strcat (filepath, fi.filenames[pos].str); Stat (Filep Ath, &buf); if (S_isdir (Buf.st_mode)) {//* if it is a directory, it will be shaded into a blue bold font/printf ("/033[01;34m");} else{/* Otherwise press the default color display */printf ("/033[0m");} printf (Fi.formats[j],fi.filenames[pos]);} else if (I&LT;FI.I) {break;} else{Putchar ('/n '); return;} Putchar (' n '); printf ("/33[0m");/* Restore shader Settings/free (filepath);} int main (int argc, char **argv) {if (ARGC < 1) {printf ("wrong usage/n"); Exit (1); }else if (argc = = 1) {My_ls (".");} else{My_ls (argv[1]);} return 0; }

Save it as "my_ls.c" and compile the executable file as "dir"

[Hang@localhost test]$ gcc my_ls.c-o dir

List the contents of my current directory, and if you compile the executable file that specifies its output in the current directory, remember that it is best to precede it with "./" in the runtime.

[Hang@localhost test]$./dir ~/

The results of the operation are as follows:

Of course, the code still has deficiencies, such as the output of the list of file names redirected to a file, it will be the color of the terminal escape character Fuye input into the inside ...

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.