mkfs, mkproto: minor improvements
[minix.git] / commands / ls / ls.c
blob67965aa596a98a9d75432bf66a9c7c7931c6807d
1 /* ls 5.4 - List files. Author: Kees J. Bot
2 * 25 Apr 1989
4 * About the amount of bytes for heap + stack under Minix:
5 * Ls needs a average amount of 42 bytes per unserviced directory entry, so
6 * scanning 10 directory levels deep in an ls -R with 100 entries per directory
7 * takes 42000 bytes of heap. So giving ls 10000 bytes is tight, 20000 is
8 * usually enough, 40000 is pessimistic.
9 */
11 /* The array l_ifmt[] is used in an 'ls -l' to map the type of a file to a
12 * letter. This is done so that ls can list any future file or device type
13 * other than symlinks, without recompilation. (Yes it's dirty.)
15 char l_ifmt[] = "0pcCd?bB-?l?s???";
17 #define ifmt(mode) l_ifmt[((mode) >> 12) & 0xF]
19 #define nil 0
20 #include <stdio.h>
21 #include <string.h>
22 #include <sys/types.h>
23 #include <sys/stat.h>
24 #include <stddef.h>
25 #include <stdlib.h>
26 #include <unistd.h>
27 #include <dirent.h>
28 #include <time.h>
29 #include <pwd.h>
30 #include <grp.h>
31 #include <errno.h>
32 #include <fcntl.h>
33 #include <limits.h>
34 #include <termios.h>
35 #include <sys/ioctl.h>
37 #ifndef major
38 #define major(dev) ((int) (((dev) >> 8) & 0xFF))
39 #define minor(dev) ((int) (((dev) >> 0) & 0xFF))
40 #endif
42 #if !__minix
43 #define SUPER_ID uid /* Let -A flag be default for SUPER_ID == 0. */
44 #else
45 #define SUPER_ID gid
46 #endif
48 #ifdef S_IFLNK
49 int (*status)(const char *file, struct stat *stp);
50 #else
51 #define status stat
52 #endif
54 /* Basic disk block size is 512 except for one niche O.S. */
55 #if __minix
56 #define BLOCK 1024
57 #else
58 #define BLOCK 512
59 #endif
61 /* Assume other systems have st_blocks. */
62 #if !__minix
63 #define ST_BLOCKS 1
64 #endif
66 /* Some terminals ignore more than 80 characters on a line. Dumb ones wrap
67 * when the cursor hits the side. Nice terminals don't wrap until they have
68 * to print the 81st character. Whether we like it or not, no column 80.
70 int ncols= 79;
72 #define NSEP 3 /* # spaces between columns. */
74 #define MAXCOLS 128 /* Max # of files per line. */
76 char *arg0; /* Last component of argv[0]. */
77 int uid, gid; /* callers id. */
78 int ex= 0; /* Exit status to be. */
79 int istty; /* Output is on a terminal. */
81 /* Safer versions of malloc and realloc: */
83 void heaperr(void)
85 fprintf(stderr, "%s: Out of memory\n", arg0);
86 exit(-1);
89 void *allocate(size_t n)
90 /* Deliver or die. */
92 void *a;
94 if ((a= malloc(n)) == nil) heaperr();
95 return a;
98 void *reallocate(void *a, size_t n)
100 if ((a= realloc(a, n)) == nil) heaperr();
101 return a;
104 char allowed[] = "acdfghilnpqrstu1ACDFLMRTX";
105 char flags[sizeof(allowed)];
107 char arg0flag[] = "cdfmrtx"; /* These in argv[0] go to upper case. */
109 void setflags(char *flgs)
111 int c;
113 while ((c= *flgs++) != 0) {
114 if (strchr(allowed, c) == nil) {
115 fprintf(stderr, "Usage: %s [-%s] [file ...]\n",
116 arg0, allowed);
117 exit(1);
118 } else
119 if (strchr(flags, c) == nil) {
120 flags[strlen(flags)] = c;
125 int present(int f)
127 return f == 0 || strchr(flags, f) != nil;
130 void report(char *f)
131 /* Like perror(3), but in the style: "ls: junk: No such file or directory. */
133 fprintf(stderr, "%s: %s: %s\n", arg0, f, strerror(errno));
134 ex= 1;
137 /* Two functions, uidname and gidname, translate id's to readable names.
138 * All names are remembered to avoid searching the password file.
140 #define NNAMES (1 << (sizeof(int) + sizeof(char *)))
141 enum whatmap { PASSWD, GROUP };
143 struct idname { /* Hash list of names. */
144 struct idname *next;
145 char *name;
146 uid_t id;
147 } *uids[NNAMES], *gids[NNAMES];
149 char *idname(unsigned id, enum whatmap map)
150 /* Return name for a given user/group id. */
152 struct idname *i;
153 struct idname **ids= &(map == PASSWD ? uids : gids)[id % NNAMES];
155 while ((i= *ids) != nil && id < i->id) ids= &i->next;
157 if (i == nil || id != i->id) {
158 /* Not found, go look in the password or group map. */
159 char *name= nil;
160 char noname[3 * sizeof(uid_t)];
162 if (!present('n')) {
163 if (map == PASSWD) {
164 struct passwd *pw= getpwuid(id);
166 if (pw != nil) name= pw->pw_name;
167 } else {
168 struct group *gr= getgrgid(id);
170 if (gr != nil) name= gr->gr_name;
173 if (name == nil) {
174 /* Can't find it, weird. Use numerical "name." */
175 sprintf(noname, "%u", id);
176 name= noname;
179 /* Add a new id-to-name cell. */
180 i= allocate(sizeof(*i));
181 i->id= id;
182 i->name= allocate(strlen(name) + 1);
183 strcpy(i->name, name);
184 i->next= *ids;
185 *ids= i;
187 return i->name;
190 #define uidname(uid) idname((uid), PASSWD)
191 #define gidname(gid) idname((gid), GROUP)
193 /* Path name construction, addpath adds a component, delpath removes it.
194 * The string path is used throughout the program as the file under examination.
197 char *path; /* Path name constructed in path[]. */
198 int plen= 0, pidx= 0; /* Lenght/index for path[]. */
200 void addpath(int *didx, char *name)
201 /* Add a component to path. (name may also be a full path at the first call)
202 * The index where the current path ends is stored in *pdi.
205 if (plen == 0) path= (char *) allocate((plen= 32) * sizeof(path[0]));
207 if (pidx == 1 && path[0] == '.') pidx= 0; /* Remove "." */
209 *didx= pidx; /* Record point to go back to for delpath. */
211 if (pidx > 0 && path[pidx-1] != '/') path[pidx++]= '/';
213 do {
214 if (*name != '/' || pidx == 0 || path[pidx-1] != '/') {
215 if (pidx == plen) {
216 path= (char *) reallocate((void *) path,
217 (plen*= 2) * sizeof(path[0]));
219 path[pidx++]= *name;
221 } while (*name++ != 0);
223 --pidx; /* Put pidx back at the null. The path[pidx++]= '/'
224 * statement will overwrite it at the next call.
228 #define delpath(didx) (path[pidx= didx]= 0) /* Remove component. */
230 int field = 0; /* (used to be) Fields that must be printed. */
231 /* (now) Effects triggered by certain flags. */
233 #define L_INODE 0x0001 /* -i */
234 #define L_BLOCKS 0x0002 /* -s */
235 #define L_EXTRA 0x0004 /* -X */
236 #define L_MODE 0x0008 /* -lMX */
237 #define L_LONG 0x0010 /* -l */
238 #define L_GROUP 0x0020 /* -g */
239 #define L_BYTIME 0x0040 /* -tuc */
240 #define L_ATIME 0x0080 /* -u */
241 #define L_CTIME 0x0100 /* -c */
242 #define L_MARK 0x0200 /* -F */
243 #define L_MARKDIR 0x0400 /* -p */
244 #define L_TYPE 0x0800 /* -D */
245 #define L_LONGTIME 0x1000 /* -T */
246 #define L_DIR 0x2000 /* -d */
247 #define L_KMG 0x4000 /* -h */
249 struct file { /* A file plus stat(2) information. */
250 struct file *next; /* Lists are made of them. */
251 char *name; /* Null terminated name. */
252 ino_t ino;
253 mode_t mode;
254 uid_t uid;
255 gid_t gid;
256 nlink_t nlink;
257 dev_t rdev;
258 off_t size;
259 time_t mtime;
260 time_t atime;
261 time_t ctime;
262 #if ST_BLOCKS
263 long blocks;
264 #endif
267 void setstat(struct file *f, struct stat *stp)
269 f->ino= stp->st_ino;
270 f->mode= stp->st_mode;
271 f->nlink= stp->st_nlink;
272 f->uid= stp->st_uid;
273 f->gid= stp->st_gid;
274 f->rdev= stp->st_rdev;
275 f->size= stp->st_size;
276 f->mtime= stp->st_mtime;
277 f->atime= stp->st_atime;
278 f->ctime= stp->st_ctime;
279 #if ST_BLOCKS
280 f->blocks= stp->st_blocks;
281 #endif
284 #define PAST (26*7*24*3600L) /* Half a year ago. */
285 /* Between PAST and FUTURE from now a time is printed, otherwise a year. */
286 #define FUTURE ( 1*7*24*3600L) /* One week. */
288 static char *timestamp(struct file *f)
289 /* Transform the right time field into something readable. */
291 struct tm *tm;
292 time_t t;
293 static time_t now;
294 static int drift= 0;
295 static char date[] = "Jan 19 03:14:07 2038";
296 static char month[] = "JanFebMarAprMayJunJulAugSepOctNovDec";
298 t= f->mtime;
299 if (field & L_ATIME) t= f->atime;
300 if (field & L_CTIME) t= f->ctime;
302 tm= localtime(&t);
303 if (--drift < 0) { time(&now); drift= 50; } /* limit time() calls */
305 if (field & L_LONGTIME) {
306 sprintf(date, "%.3s %2d %02d:%02d:%02d %d",
307 month + 3*tm->tm_mon,
308 tm->tm_mday,
309 tm->tm_hour, tm->tm_min, tm->tm_sec,
310 1900 + tm->tm_year);
311 } else
312 if (t < now - PAST || t > now + FUTURE) {
313 sprintf(date, "%.3s %2d %d",
314 month + 3*tm->tm_mon,
315 tm->tm_mday,
316 1900 + tm->tm_year);
317 } else {
318 sprintf(date, "%.3s %2d %02d:%02d",
319 month + 3*tm->tm_mon,
320 tm->tm_mday,
321 tm->tm_hour, tm->tm_min);
323 return date;
326 char *permissions(struct file *f)
327 /* Compute long or short rwx bits. */
329 static char rwx[] = "drwxr-x--x";
331 rwx[0] = ifmt(f->mode);
332 /* Note that rwx[0] is a guess for the more alien file types. It is
333 * correct for BSD4.3 and derived systems. I just don't know how
334 * "standardized" these numbers are.
337 if (field & L_EXTRA) { /* Short style */
338 int mode = f->mode, ucase= 0;
340 if (uid == f->uid) { /* What group of bits to use. */
341 /* mode<<= 0, */
342 ucase= (mode<<3) | (mode<<6);
343 /* Remember if group or others have permissions. */
344 } else
345 if (gid == f->gid) {
346 mode<<= 3;
347 } else {
348 mode<<= 6;
350 rwx[1]= mode&S_IRUSR ? (ucase&S_IRUSR ? 'R' : 'r') : '-';
351 rwx[2]= mode&S_IWUSR ? (ucase&S_IWUSR ? 'W' : 'w') : '-';
353 if (mode&S_IXUSR) {
354 static char sbit[]= { 'x', 'g', 'u', 's' };
356 rwx[3]= sbit[(f->mode&(S_ISUID|S_ISGID))>>10];
357 if (ucase&S_IXUSR) rwx[3] += 'A'-'a';
358 } else {
359 rwx[3]= f->mode&(S_ISUID|S_ISGID) ? '=' : '-';
361 rwx[4]= 0;
362 } else { /* Long form. */
363 char *p= rwx+1;
364 int mode= f->mode;
366 do {
367 p[0] = (mode & S_IRUSR) ? 'r' : '-';
368 p[1] = (mode & S_IWUSR) ? 'w' : '-';
369 p[2] = (mode & S_IXUSR) ? 'x' : '-';
370 mode<<= 3;
371 } while ((p+=3) <= rwx+7);
373 if (f->mode&S_ISUID) rwx[3]= f->mode&(S_IXUSR>>0) ? 's' : '=';
374 if (f->mode&S_ISGID) rwx[6]= f->mode&(S_IXUSR>>3) ? 's' : '=';
375 if (f->mode&S_ISVTX) rwx[9]= f->mode&(S_IXUSR>>6) ? 't' : '=';
377 return rwx;
380 void numeral(int i, char **pp)
382 char itoa[3*sizeof(int)], *a=itoa;
384 do *a++ = i%10 + '0'; while ((i/=10) > 0);
386 do *(*pp)++ = *--a; while (a>itoa);
389 #define K 1024L /* A kilobyte counts in multiples of K */
390 #define T 1000L /* A megabyte in T*K, a gigabyte in T*T*K */
392 char *cxsize(struct file *f)
393 /* Try and fail to turn a 32 bit size into 4 readable characters. */
395 static char siz[] = "1.2m";
396 char *p= siz;
397 off_t z;
399 siz[1]= siz[2]= siz[3]= 0;
401 if (f->size <= 5*K) { /* <= 5K prints as is. */
402 numeral((int) f->size, &p);
403 return siz;
405 z= (f->size + K-1) / K;
407 if (z <= 999) { /* Print as 123k. */
408 numeral((int) z, &p);
409 *p = 'k'; /* Can't use 'K', looks bad */
410 } else
411 if (z*10 <= 99*T) { /* 1.2m (Try ls -X /dev/at0) */
412 z= (z*10 + T-1) / T; /* Force roundup */
413 numeral((int) z / 10, &p);
414 *p++ = '.';
415 numeral((int) z % 10, &p);
416 *p = 'm';
417 } else
418 if (z <= 999*T) { /* 123m */
419 numeral((int) ((z + T-1) / T), &p);
420 *p = 'm';
421 } else { /* 1.2g */
422 z= (z*10 + T*T-1) / (T*T);
423 numeral((int) z / 10, &p);
424 *p++ = '.';
425 numeral((int) z % 10, &p);
426 *p = 'g';
428 return siz;
431 /* Transform size of file to number of blocks. This was once a function that
432 * guessed the number of indirect blocks, but that nonsense has been removed.
434 #if ST_BLOCKS
435 #define nblocks(f) ((f)->blocks)
436 #else
437 #define nblocks(f) (((f)->size + BLOCK-1) / BLOCK)
438 #endif
440 /* From number of blocks to kilobytes. */
441 #if BLOCK < 1024
442 #define nblk2k(nb) (((nb) + (1024 / BLOCK - 1)) / (1024 / BLOCK))
443 #else
444 #define nblk2k(nb) ((nb) * (BLOCK / 1024))
445 #endif
447 static int (*CMP)(struct file *f1, struct file *f2);
448 static int (*rCMP)(struct file *f1, struct file *f2);
450 #ifdef __NBSD_LIBC
451 #define mergesort _ls_mergesort
452 #endif
454 static void mergesort(struct file **al)
455 /* This is either a stable mergesort, or thermal noise, I'm no longer sure.
456 * It must be called like this: if (L != nil && L->next != nil) mergesort(&L);
459 /* static */ struct file *l1, **mid; /* Need not be local */
460 struct file *l2;
462 l1= *(mid= &(*al)->next);
463 do {
464 if ((l1= l1->next) == nil) break;
465 mid= &(*mid)->next;
466 } while ((l1= l1->next) != nil);
468 l2= *mid;
469 *mid= nil;
471 if ((*al)->next != nil) mergesort(al);
472 if (l2->next != nil) mergesort(&l2);
474 l1= *al;
475 for (;;) {
476 if ((*CMP)(l1, l2) <= 0) {
477 if ((l1= *(al= &l1->next)) == nil) {
478 *al= l2;
479 break;
481 } else {
482 *al= l2;
483 l2= *(al= &l2->next);
484 *al= l1;
485 if (l2 == nil) break;
490 int namecmp(struct file *f1, struct file *f2)
492 return strcmp(f1->name, f2->name);
495 int mtimecmp(struct file *f1, struct file *f2)
497 return f1->mtime == f2->mtime ? 0 : f1->mtime > f2->mtime ? -1 : 1;
500 int atimecmp(struct file *f1, struct file *f2)
502 return f1->atime == f2->atime ? 0 : f1->atime > f2->atime ? -1 : 1;
505 int ctimecmp(struct file *f1, struct file *f2)
507 return f1->ctime == f2->ctime ? 0 : f1->ctime > f2->ctime ? -1 : 1;
510 int typecmp(struct file *f1, struct file *f2)
512 return ifmt(f1->mode) - ifmt(f2->mode);
515 int revcmp(struct file *f1, struct file *f2) { return (*rCMP)(f2, f1); }
517 static void sort(struct file **al)
518 /* Sort the files according to the flags. */
520 if (!present('f') && *al != nil && (*al)->next != nil) {
521 CMP= namecmp;
523 if (!(field & L_BYTIME)) {
524 /* Sort on name */
526 if (present('r')) { rCMP= CMP; CMP= revcmp; }
527 mergesort(al);
528 } else {
529 /* Sort on name first, then sort on time. */
531 mergesort(al);
532 if (field & L_CTIME) {
533 CMP= ctimecmp;
534 } else
535 if (field & L_ATIME) {
536 CMP= atimecmp;
537 } else {
538 CMP= mtimecmp;
541 if (present('r')) { rCMP= CMP; CMP= revcmp; }
542 mergesort(al);
544 /* Separate by file type if so desired. */
546 if (field & L_TYPE) {
547 CMP= typecmp;
548 mergesort(al);
553 struct file *newfile(char *name)
554 /* Create file structure for given name. */
556 struct file *new;
558 new= (struct file *) allocate(sizeof(*new));
559 new->name= strcpy((char *) allocate(strlen(name)+1), name);
560 return new;
563 void pushfile(struct file **flist, struct file *new)
564 /* Add file to the head of a list. */
566 new->next= *flist;
567 *flist= new;
570 void delfile(struct file *old)
571 /* Release old file structure. */
573 free((void *) old->name);
574 free((void *) old);
577 struct file *popfile(struct file **flist)
578 /* Pop file off top of file list. */
580 struct file *f;
582 f= *flist;
583 *flist= f->next;
584 return f;
587 int dotflag(char *name)
588 /* Return flag that would make ls list this name: -a or -A. */
590 if (*name++ != '.') return 0;
592 switch (*name++) {
593 case 0: return 'a'; /* "." */
594 case '.': if (*name == 0) return 'a'; /* ".." */
595 default: return 'A'; /* ".*" */
599 int adddir(struct file **aflist, char *name)
600 /* Add directory entries of directory name to a file list. */
602 DIR *d;
603 struct dirent *e;
605 if (access(name, 0) < 0) {
606 report(name);
607 return 0;
610 if ((d= opendir(name)) == nil) {
611 report(name);
612 return 0;
614 while ((e= readdir(d)) != nil) {
615 if (e->d_ino != 0 && present(dotflag(e->d_name))) {
616 pushfile(aflist, newfile(e->d_name));
617 aflist= &(*aflist)->next;
620 closedir(d);
621 return 1;
624 off_t countblocks(struct file *flist)
625 /* Compute total block count for a list of files. */
627 off_t cb = 0;
629 while (flist != nil) {
630 switch (flist->mode & S_IFMT) {
631 case S_IFDIR:
632 case S_IFREG:
633 #ifdef S_IFLNK
634 case S_IFLNK:
635 #endif
636 cb += nblocks(flist);
638 flist= flist->next;
640 return cb;
643 void printname(char *name)
644 /* Print a name with control characters as '?' (unless -q). The terminal is
645 * assumed to be eight bit clean.
648 int c, q= present('q');
650 while ((c= (unsigned char) *name++) != 0) {
651 if (q && (c < ' ' || c == 0177)) c= '?';
652 putchar(c);
656 int mark(struct file *f, int doit)
658 int c;
660 c= 0;
662 if (field & L_MARK) {
663 switch (f->mode & S_IFMT) {
664 case S_IFDIR: c= '/'; break;
665 #ifdef S_IFIFO
666 case S_IFIFO: c= '|'; break;
667 #endif
668 #ifdef S_IFLNK
669 case S_IFLNK: c= '@'; break;
670 #endif
671 #ifdef S_IFSOCK
672 case S_IFSOCK: c= '='; break;
673 #endif
674 case S_IFREG:
675 if (f->mode & (S_IXUSR | S_IXGRP | S_IXOTH)) c= '*';
676 break;
678 } else
679 if (field & L_MARKDIR) {
680 if (S_ISDIR(f->mode)) c= '/';
683 if (doit && c != 0) putchar(c);
684 return c;
687 /* Width of entire column, and of several fields. */
688 enum { W_COL, W_INO, W_BLK, W_NLINK, W_UID, W_GID, W_SIZE, W_NAME, MAXFLDS };
690 unsigned char fieldwidth[MAXCOLS][MAXFLDS];
692 void maxise(unsigned char *aw, int w)
693 /* Set *aw to the larger of it and w. */
695 if (w > *aw) {
696 if (w > UCHAR_MAX) w= UCHAR_MAX;
697 *aw= w;
701 int numwidth(unsigned long n)
702 /* Compute width of 'n' when printed. */
704 int width= 0;
706 do { width++; } while ((n /= 10) > 0);
707 return width;
710 #if !__minix
711 int numxwidth(unsigned long n)
712 /* Compute width of 'n' when printed in hex. */
714 int width= 0;
716 do { width++; } while ((n /= 16) > 0);
717 return width;
719 #endif
721 static int nsp= 0; /* This many spaces have not been printed yet. */
722 #define spaces(n) (nsp= (n))
723 #define terpri() (nsp= 0, putchar('\n')) /* No trailing spaces */
725 void print1(struct file *f, int col, int doit)
726 /* Either compute the number of spaces needed to print file f (doit == 0) or
727 * really print it (doit == 1).
730 int width= 0, n;
731 char *p;
732 unsigned char *f1width = fieldwidth[col];
734 while (nsp>0) { putchar(' '); nsp--; }/* Fill gap between two columns */
736 if (field & L_INODE) {
737 if (doit) {
738 printf("%*d ", f1width[W_INO], f->ino);
739 } else {
740 maxise(&f1width[W_INO], numwidth(f->ino));
741 width++;
744 if (field & L_BLOCKS) {
745 unsigned long nb= nblk2k(nblocks(f));
746 if (doit) {
747 printf("%*lu ", f1width[W_BLK], nb);
748 } else {
749 maxise(&f1width[W_BLK], numwidth(nb));
750 width++;
753 if (field & L_MODE) {
754 if (doit) {
755 printf("%s ", permissions(f));
756 } else {
757 width+= (field & L_EXTRA) ? 5 : 11;
760 if (field & L_EXTRA) {
761 p= cxsize(f);
762 n= strlen(p)+1;
764 if (doit) {
765 n= f1width[W_SIZE] - n;
766 while (n > 0) { putchar(' '); --n; }
767 printf("%s ", p);
768 } else {
769 maxise(&f1width[W_SIZE], n);
772 if (field & L_LONG) {
773 if (doit) {
774 printf("%*u ", f1width[W_NLINK], (unsigned) f->nlink);
775 } else {
776 maxise(&f1width[W_NLINK], numwidth(f->nlink));
777 width++;
779 if (!(field & L_GROUP)) {
780 if (doit) {
781 printf("%-*s ", f1width[W_UID],
782 uidname(f->uid));
783 } else {
784 maxise(&f1width[W_UID],
785 strlen(uidname(f->uid)));
786 width+= 2;
789 if (doit) {
790 printf("%-*s ", f1width[W_GID], gidname(f->gid));
791 } else {
792 maxise(&f1width[W_GID], strlen(gidname(f->gid)));
793 width+= 2;
796 switch (f->mode & S_IFMT) {
797 case S_IFBLK:
798 case S_IFCHR:
799 #ifdef S_IFMPB
800 case S_IFMPB:
801 #endif
802 #ifdef S_IFMPC
803 case S_IFMPC:
804 #endif
805 #if __minix
806 if (doit) {
807 printf("%*d, %3d ", f1width[W_SIZE] - 5,
808 major(f->rdev), minor(f->rdev));
809 } else {
810 maxise(&f1width[W_SIZE],
811 numwidth(major(f->rdev)) + 5);
812 width++;
814 #else /* !__minix */
815 if (doit) {
816 printf("%*lX ", f1width[W_SIZE],
817 (unsigned long) f->rdev);
818 } else {
819 maxise(&f1width[W_SIZE], numwidth(f->rdev));
820 width++;
822 #endif /* !__minix */
823 break;
824 default:
825 if (field & L_KMG) {
826 p= cxsize(f);
827 n= strlen(p)+1;
829 if (doit) {
830 n= f1width[W_SIZE] - n;
831 while (n > 0) { putchar(' '); --n; }
832 printf("%s ", p);
833 } else {
834 maxise(&f1width[W_SIZE], n);
836 } else {
837 if (doit) {
838 printf("%*lu ", f1width[W_SIZE],
839 (unsigned long) f->size);
840 } else {
841 maxise(&f1width[W_SIZE],
842 numwidth(f->size));
843 width++;
848 if (doit) {
849 printf("%s ", timestamp(f));
850 } else {
851 width+= (field & L_LONGTIME) ? 21 : 13;
855 n= strlen(f->name);
856 if (doit) {
857 printname(f->name);
858 if (mark(f, 1) != 0) n++;
859 #ifdef S_IFLNK
860 if ((field & L_LONG) && (f->mode & S_IFMT) == S_IFLNK) {
861 char *buf;
862 int r, didx;
864 buf= (char *) allocate(((size_t) f->size + 1)
865 * sizeof(buf[0]));
866 addpath(&didx, f->name);
867 r= readlink(path, buf, (int) f->size);
868 delpath(didx);
869 if (r > 0) buf[r] = 0; else r=1, strcpy(buf, "?");
870 printf(" -> ");
871 printname(buf);
872 free((void *) buf);
873 n+= 4 + r;
875 #endif
876 spaces(f1width[W_NAME] - n);
877 } else {
878 if (mark(f, 0) != 0) n++;
879 #ifdef S_IFLNK
880 if ((field & L_LONG) && (f->mode & S_IFMT) == S_IFLNK) {
881 n+= 4 + (int) f->size;
883 #endif
884 maxise(&f1width[W_NAME], n + NSEP);
886 for (n= 1; n < MAXFLDS; n++) width+= f1width[n];
887 maxise(&f1width[W_COL], width);
891 int countfiles(struct file *flist)
892 /* Return number of files in the list. */
894 int n= 0;
896 while (flist != nil) { n++; flist= flist->next; }
898 return n;
901 struct file *filecol[MAXCOLS]; /* filecol[i] is list of files for column i. */
902 int nfiles, nlines; /* # files to print, # of lines needed. */
904 void columnise(struct file *flist, int nplin)
905 /* Chop list of files up in columns. Note that 3 columns are used for 5 files
906 * even though nplin may be 4, filecol[3] will simply be nil.
909 int i, j;
911 nlines= (nfiles + nplin - 1) / nplin; /* nlines needed for nfiles */
913 filecol[0]= flist;
915 for (i=1; i<nplin; i++) { /* Give nlines files to each column. */
916 for (j=0; j<nlines && flist != nil; j++) flist= flist->next;
918 filecol[i]= flist;
922 int print(struct file *flist, int nplin, int doit)
923 /* Try (doit == 0), or really print the list of files over nplin columns.
924 * Return true if it can be done in nplin columns or if nplin == 1.
927 register struct file *f;
928 register int col, fld, totlen;
930 columnise(flist, nplin);
932 if (!doit) {
933 for (col= 0; col < nplin; col++) {
934 for (fld= 0; fld < MAXFLDS; fld++) {
935 fieldwidth[col][fld]= 0;
940 while (--nlines >= 0) {
941 totlen= 0;
943 for (col= 0; col < nplin; col++) {
944 if ((f= filecol[col]) != nil) {
945 filecol[col]= f->next;
946 print1(f, col, doit);
948 if (!doit && nplin > 1) {
949 /* See if this line is not too long. */
950 if (fieldwidth[col][W_COL] == UCHAR_MAX) {
951 return 0;
953 totlen+= fieldwidth[col][W_COL];
954 if (totlen > ncols+NSEP) return 0;
957 if (doit) terpri();
959 return 1;
962 enum depth { SURFACE, SURFACE1, SUBMERGED };
963 enum state { BOTTOM, SINKING, FLOATING };
965 void listfiles(struct file *flist, enum depth depth, enum state state)
966 /* Main workhorse of ls, it sorts and prints the list of files. Flags:
967 * depth: working with the command line / just one file / listing dir.
968 * state: How "recursive" do we have to be.
971 struct file *dlist= nil, **afl= &flist, **adl= &dlist;
972 int nplin;
973 static int white = 1; /* Nothing printed yet. */
975 /* Flush everything previously printed, so new error output will
976 * not intermix with files listed earlier.
978 fflush(stdout);
980 if (field != 0 || state != BOTTOM) { /* Need stat(2) info. */
981 while (*afl != nil) {
982 static struct stat st;
983 int r, didx;
985 addpath(&didx, (*afl)->name);
987 if ((r= status(path, &st)) < 0
988 #ifdef S_IFLNK
989 && (status == lstat || lstat(path, &st) < 0)
990 #endif
992 if (depth != SUBMERGED || errno != ENOENT)
993 report((*afl)->name);
994 delfile(popfile(afl));
995 } else {
996 setstat(*afl, &st);
997 afl= &(*afl)->next;
999 delpath(didx);
1002 sort(&flist);
1004 if (depth == SUBMERGED && (field & (L_BLOCKS | L_LONG))) {
1005 printf("total %ld\n", nblk2k(countblocks(flist)));
1008 if (state == SINKING || depth == SURFACE1) {
1009 /* Don't list directories themselves, list their contents later. */
1010 afl= &flist;
1011 while (*afl != nil) {
1012 if (((*afl)->mode & S_IFMT) == S_IFDIR) {
1013 pushfile(adl, popfile(afl));
1014 adl= &(*adl)->next;
1015 } else {
1016 afl= &(*afl)->next;
1021 if ((nfiles= countfiles(flist)) > 0) {
1022 /* Print files in how many columns? */
1023 nplin= !present('C') ? 1 : nfiles < MAXCOLS ? nfiles : MAXCOLS;
1025 while (!print(flist, nplin, 0)) nplin--; /* Try first */
1027 print(flist, nplin, 1); /* Then do it! */
1028 white = 0;
1031 while (flist != nil) { /* Destroy file list */
1032 if (state == FLOATING && (flist->mode & S_IFMT) == S_IFDIR) {
1033 /* But keep these directories for ls -R. */
1034 pushfile(adl, popfile(&flist));
1035 adl= &(*adl)->next;
1036 } else {
1037 delfile(popfile(&flist));
1041 while (dlist != nil) { /* List directories */
1042 if (dotflag(dlist->name) != 'a' || depth != SUBMERGED) {
1043 int didx;
1045 addpath(&didx, dlist->name);
1047 flist= nil;
1048 if (adddir(&flist, path)) {
1049 if (depth != SURFACE1) {
1050 if (!white) putchar('\n');
1051 printf("%s:\n", path);
1052 white = 0;
1054 listfiles(flist, SUBMERGED,
1055 state == FLOATING ? FLOATING : BOTTOM);
1057 delpath(didx);
1059 delfile(popfile(&dlist));
1063 int main(int argc, char **argv)
1065 struct file *flist= nil, **aflist= &flist;
1066 enum depth depth;
1067 char *lsflags;
1068 struct winsize ws;
1070 uid= geteuid();
1071 gid= getegid();
1073 if ((arg0= strrchr(argv[0], '/')) == nil) arg0= argv[0]; else arg0++;
1074 argv++;
1076 if (strcmp(arg0, "ls") != 0) {
1077 char *p= arg0+1;
1079 while (*p != 0) {
1080 if (strchr(arg0flag, *p) != nil) *p += 'A' - 'a';
1081 p++;
1083 setflags(arg0+1);
1085 while (*argv != nil && (*argv)[0] == '-') {
1086 if ((*argv)[1] == '-' && (*argv)[2] == 0) {
1087 argv++;
1088 break;
1090 setflags(*argv++ + 1);
1093 istty= isatty(1);
1095 if (istty && (lsflags= getenv("LSOPTS")) != nil) {
1096 if (*lsflags == '-') lsflags++;
1097 setflags(lsflags);
1100 if (!present('1') && !present('C') && !present('l')
1101 && (istty || present('M') || present('X') || present('F'))
1102 ) setflags("C");
1104 if (istty) setflags("q");
1106 if (SUPER_ID == 0 || present('a')) setflags("A");
1108 if (present('i')) field|= L_INODE;
1109 if (present('s')) field|= L_BLOCKS;
1110 if (present('M')) field|= L_MODE;
1111 if (present('X')) field|= L_EXTRA | L_MODE;
1112 if (present('t')) field|= L_BYTIME;
1113 if (present('u')) field|= L_ATIME;
1114 if (present('c')) field|= L_CTIME;
1115 if (present('l')) field|= L_MODE | L_LONG;
1116 if (present('g')) field|= L_MODE | L_LONG | L_GROUP;
1117 if (present('F')) field|= L_MARK;
1118 if (present('p')) field|= L_MARKDIR;
1119 if (present('D')) field|= L_TYPE;
1120 if (present('T')) field|= L_MODE | L_LONG | L_LONGTIME;
1121 if (present('d')) field|= L_DIR;
1122 if (present('h')) field|= L_KMG;
1123 if (field & L_LONG) field&= ~L_EXTRA;
1125 #ifdef S_IFLNK
1126 status= present('L') ? stat : lstat;
1127 #endif
1129 if (present('C')) {
1130 int t= istty ? 1 : open("/dev/tty", O_WRONLY);
1132 if (t >= 0 && ioctl(t, TIOCGWINSZ, &ws) == 0 && ws.ws_col > 0)
1133 ncols= ws.ws_col - 1;
1135 if (t != 1 && t != -1) close(t);
1138 depth= SURFACE;
1140 if (*argv == nil) {
1141 if (!(field & L_DIR)) depth= SURFACE1;
1142 pushfile(aflist, newfile("."));
1143 } else {
1144 if (argv[1] == nil && !(field & L_DIR)) depth= SURFACE1;
1146 do {
1147 pushfile(aflist, newfile(*argv++));
1148 aflist= &(*aflist)->next;
1149 } while (*argv!=nil);
1151 listfiles(flist, depth,
1152 (field & L_DIR) ? BOTTOM : present('R') ? FLOATING : SINKING);
1153 return ex;