diff options
Diffstat (limited to 'coreutils')
-rw-r--r-- | coreutils/cat.c | 54 | ||||
-rw-r--r-- | coreutils/chroot.c | 57 | ||||
-rw-r--r-- | coreutils/date.c | 451 | ||||
-rw-r--r-- | coreutils/dd.c | 284 | ||||
-rw-r--r-- | coreutils/df.c | 119 | ||||
-rw-r--r-- | coreutils/du.c | 185 | ||||
-rw-r--r-- | coreutils/head.c | 134 | ||||
-rw-r--r-- | coreutils/hostid.c | 8 | ||||
-rw-r--r-- | coreutils/length.c | 14 | ||||
-rw-r--r-- | coreutils/ln.c | 150 | ||||
-rw-r--r-- | coreutils/logname.c | 22 | ||||
-rw-r--r-- | coreutils/ls.c | 297 | ||||
-rw-r--r-- | coreutils/mkdir.c | 133 | ||||
-rw-r--r-- | coreutils/mkfifo.c | 64 | ||||
-rw-r--r-- | coreutils/mknod.c | 39 | ||||
-rw-r--r-- | coreutils/printf.c | 632 | ||||
-rw-r--r-- | coreutils/pwd.c | 12 | ||||
-rw-r--r-- | coreutils/rm.c | 102 | ||||
-rw-r--r-- | coreutils/rmdir.c | 20 | ||||
-rw-r--r-- | coreutils/sleep.c | 19 | ||||
-rw-r--r-- | coreutils/sort.c | 385 | ||||
-rw-r--r-- | coreutils/sync.c | 13 | ||||
-rw-r--r-- | coreutils/tail.c | 1789 | ||||
-rw-r--r-- | coreutils/tee.c | 129 | ||||
-rw-r--r-- | coreutils/touch.c | 79 | ||||
-rw-r--r-- | coreutils/tty.c | 25 | ||||
-rw-r--r-- | coreutils/uname.c | 139 | ||||
-rw-r--r-- | coreutils/uniq.c | 225 | ||||
-rw-r--r-- | coreutils/wc.c | 127 | ||||
-rw-r--r-- | coreutils/whoami.c | 27 | ||||
-rw-r--r-- | coreutils/yes.c | 14 |
31 files changed, 2841 insertions, 2907 deletions
diff --git a/coreutils/cat.c b/coreutils/cat.c index 0d32efe84..86f85fe8e 100644 --- a/coreutils/cat.c +++ b/coreutils/cat.c @@ -1,3 +1,4 @@ +/* vi: set sw=4 ts=4: */ /* * Mini Cat implementation for busybox * @@ -24,36 +25,37 @@ #include <stdio.h> -static void print_file( FILE *file) +static void print_file(FILE * file) { - int c; - while ((c = getc(file)) != EOF) - putc(c, stdout); - fclose(file); - fflush(stdout); + int c; + + while ((c = getc(file)) != EOF) + putc(c, stdout); + fclose(file); + fflush(stdout); } extern int cat_main(int argc, char **argv) { - FILE *file; - - if (argc==1) { - print_file( stdin); - exit( TRUE); - } - - if ( **(argv+1) == '-' ) { - usage ("cat [file ...]\n"); - } - argc--; - - while (argc-- > 0 && *(argv++) != '\0' && strlen(*argv) ) { - file = fopen(*argv, "r"); - if (file == NULL) { - perror(*argv); - exit(FALSE); + FILE *file; + + if (argc == 1) { + print_file(stdin); + exit(TRUE); + } + + if (**(argv + 1) == '-') { + usage("cat [file ...]\n"); + } + argc--; + + while (argc-- > 0 && *(argv++) != '\0' && strlen(*argv)) { + file = fopen(*argv, "r"); + if (file == NULL) { + perror(*argv); + exit(FALSE); + } + print_file(file); } - print_file( file); - } - exit(TRUE); + exit(TRUE); } diff --git a/coreutils/chroot.c b/coreutils/chroot.c index 16524d92e..6a01be603 100644 --- a/coreutils/chroot.c +++ b/coreutils/chroot.c @@ -1,3 +1,4 @@ +/* vi: set sw=4 ts=4: */ /* * Mini chroot implementation for busybox * @@ -28,39 +29,39 @@ static const char chroot_usage[] = "chroot NEWROOT [COMMAND...]\n\n" -"Run COMMAND with root directory set to NEWROOT.\n"; + + "Run COMMAND with root directory set to NEWROOT.\n"; int chroot_main(int argc, char **argv) { - if ( (argc < 2) || (**(argv+1) == '-') ) { - usage( chroot_usage); - } - argc--; - argv++; + if ((argc < 2) || (**(argv + 1) == '-')) { + usage(chroot_usage); + } + argc--; + argv++; - if (chroot (*argv) || (chdir ("/"))) { - fprintf(stderr, "chroot: cannot change root directory to %s: %s\n", - *argv, strerror(errno)); - exit( FALSE); - } + if (chroot(*argv) || (chdir("/"))) { + fprintf(stderr, "chroot: cannot change root directory to %s: %s\n", + *argv, strerror(errno)); + exit(FALSE); + } - argc--; - argv++; - if (argc >= 1) { - fprintf(stderr, "command: %s\n", *argv); - execvp (*argv, argv); - } - else { - char *prog; - prog = getenv ("SHELL"); - if (!prog) - prog = "/bin/sh"; - execlp (prog, prog, NULL); - } - fprintf(stderr, "chroot: cannot execute %s: %s\n", - *argv, strerror(errno)); - exit( FALSE); -} + argc--; + argv++; + if (argc >= 1) { + fprintf(stderr, "command: %s\n", *argv); + execvp(*argv, argv); + } else { + char *prog; + prog = getenv("SHELL"); + if (!prog) + prog = "/bin/sh"; + execlp(prog, prog, NULL); + } + fprintf(stderr, "chroot: cannot execute %s: %s\n", + *argv, strerror(errno)); + exit(FALSE); +} diff --git a/coreutils/date.c b/coreutils/date.c index a3528921d..b4c3e7153 100644 --- a/coreutils/date.c +++ b/coreutils/date.c @@ -1,3 +1,4 @@ +/* vi: set sw=4 ts=4: */ /* * Mini date implementation for busybox * @@ -38,12 +39,13 @@ an RFC 822 complient date output for shell scripting mail commands */ -static const char date_usage[] = "date [OPTION]... [+FORMAT]\n" -" or: date [OPTION] [MMDDhhmm[[CC]YY][.ss]]\n\n" -"Display the current time in the given FORMAT, or set the system date.\n" -"\nOptions:\n\t-R\t\toutput RFC-822 compliant date string\n" -"\t-s\t\tset time described by STRING\n" -"\t-u\t\tprint or set Coordinated Universal Time\n"; +static const char date_usage[] = "date [OPTION]... [+FORMAT]\n" + " or: date [OPTION] [MMDDhhmm[[CC]YY][.ss]]\n\n" + "Display the current time in the given FORMAT, or set the system date.\n" + "\nOptions:\n\t-R\t\toutput RFC-822 compliant date string\n" + "\t-s\t\tset time described by STRING\n" + + "\t-u\t\tprint or set Coordinated Universal Time\n"; /* Input parsing code is always bulky - used heavy duty libc stuff as @@ -51,240 +53,233 @@ static const char date_usage[] = "date [OPTION]... [+FORMAT]\n" /* Default input handling to save suprising some people */ -struct tm * -date_conv_time(struct tm *tm_time, const char *t_string) { - int nr; - - nr = sscanf(t_string, "%2d%2d%2d%2d%d", - &(tm_time->tm_mon), - &(tm_time->tm_mday), - &(tm_time->tm_hour), - &(tm_time->tm_min), - &(tm_time->tm_year)); - - if(nr < 4 || nr > 5) { - fprintf(stderr, invalid_date, "date", t_string); - exit( FALSE); - } - - /* correct for century - minor Y2K problem here? */ - if(tm_time->tm_year >= 1900) - tm_time->tm_year -= 1900; - /* adjust date */ - tm_time->tm_mon -= 1; - - return(tm_time); +struct tm *date_conv_time(struct tm *tm_time, const char *t_string) +{ + int nr; + + nr = sscanf(t_string, "%2d%2d%2d%2d%d", + &(tm_time->tm_mon), + &(tm_time->tm_mday), + &(tm_time->tm_hour), + &(tm_time->tm_min), &(tm_time->tm_year)); + + if (nr < 4 || nr > 5) { + fprintf(stderr, invalid_date, "date", t_string); + exit(FALSE); + } + + /* correct for century - minor Y2K problem here? */ + if (tm_time->tm_year >= 1900) + tm_time->tm_year -= 1900; + /* adjust date */ + tm_time->tm_mon -= 1; + + return (tm_time); } /* The new stuff for LRP */ -struct tm * -date_conv_ftime(struct tm *tm_time, const char *t_string) { - struct tm itm_time, jtm_time, ktm_time, \ - ltm_time, mtm_time, ntm_time; - - itm_time = *tm_time; - jtm_time = *tm_time; - ktm_time = *tm_time; - ltm_time = *tm_time; - mtm_time = *tm_time; - ntm_time = *tm_time; - - /* Parse input and assign appropriately to tm_time */ - - if(sscanf(t_string, "%d:%d:%d", - &itm_time.tm_hour, - &itm_time.tm_min, - &itm_time.tm_sec) == 3 ) { - - *tm_time = itm_time; - return(tm_time); - - } else if (sscanf(t_string, "%d:%d", - &jtm_time.tm_hour, - &jtm_time.tm_min) == 2) { - - *tm_time = jtm_time; - return(tm_time); - - } else if (sscanf(t_string, "%d.%d-%d:%d:%d", - &ktm_time.tm_mon, - &ktm_time.tm_mday, - &ktm_time.tm_hour, - &ktm_time.tm_min, - &ktm_time.tm_sec) == 5) { - - ktm_time.tm_mon -= 1; /* Adjust dates from 1-12 to 0-11 */ - *tm_time = ktm_time; - return(tm_time); - - } else if (sscanf(t_string, "%d.%d-%d:%d", - <m_time.tm_mon, - <m_time.tm_mday, - <m_time.tm_hour, - <m_time.tm_min) == 4) { - - ltm_time.tm_mon -= 1; /* Adjust dates from 1-12 to 0-11 */ - *tm_time = ltm_time; - return(tm_time); - - } else if (sscanf(t_string, "%d.%d.%d-%d:%d:%d", - &mtm_time.tm_year, - &mtm_time.tm_mon, - &mtm_time.tm_mday, - &mtm_time.tm_hour, - &mtm_time.tm_min, - &mtm_time.tm_sec) == 6) { - - mtm_time.tm_year -= 1900; /* Adjust years */ - mtm_time.tm_mon -= 1; /* Adjust dates from 1-12 to 0-11 */ - *tm_time = mtm_time; - return(tm_time); - - } else if (sscanf(t_string, "%d.%d.%d-%d:%d", - &ntm_time.tm_year, - &ntm_time.tm_mon, - &ntm_time.tm_mday, - &ntm_time.tm_hour, - &ntm_time.tm_min) == 5) { - ntm_time.tm_year -= 1900; /* Adjust years */ - ntm_time.tm_mon -= 1; /* Adjust dates from 1-12 to 0-11 */ - *tm_time = ntm_time; - return(tm_time); - - } - - fprintf(stderr, invalid_date, "date", t_string); - - exit( FALSE); +struct tm *date_conv_ftime(struct tm *tm_time, const char *t_string) +{ + struct tm itm_time, jtm_time, ktm_time, ltm_time, mtm_time, ntm_time; + + itm_time = *tm_time; + jtm_time = *tm_time; + ktm_time = *tm_time; + ltm_time = *tm_time; + mtm_time = *tm_time; + ntm_time = *tm_time; + + /* Parse input and assign appropriately to tm_time */ + + if (sscanf(t_string, "%d:%d:%d", + &itm_time.tm_hour, &itm_time.tm_min, &itm_time.tm_sec) == 3) { + + *tm_time = itm_time; + return (tm_time); + + } else if (sscanf(t_string, "%d:%d", + &jtm_time.tm_hour, &jtm_time.tm_min) == 2) { + + *tm_time = jtm_time; + return (tm_time); + + } else if (sscanf(t_string, "%d.%d-%d:%d:%d", + &ktm_time.tm_mon, + &ktm_time.tm_mday, + &ktm_time.tm_hour, + &ktm_time.tm_min, &ktm_time.tm_sec) == 5) { + + ktm_time.tm_mon -= 1; /* Adjust dates from 1-12 to 0-11 */ + *tm_time = ktm_time; + return (tm_time); + + } else if (sscanf(t_string, "%d.%d-%d:%d", + <m_time.tm_mon, + <m_time.tm_mday, + <m_time.tm_hour, <m_time.tm_min) == 4) { + + ltm_time.tm_mon -= 1; /* Adjust dates from 1-12 to 0-11 */ + *tm_time = ltm_time; + return (tm_time); + + } else if (sscanf(t_string, "%d.%d.%d-%d:%d:%d", + &mtm_time.tm_year, + &mtm_time.tm_mon, + &mtm_time.tm_mday, + &mtm_time.tm_hour, + &mtm_time.tm_min, &mtm_time.tm_sec) == 6) { + + mtm_time.tm_year -= 1900; /* Adjust years */ + mtm_time.tm_mon -= 1; /* Adjust dates from 1-12 to 0-11 */ + *tm_time = mtm_time; + return (tm_time); + + } else if (sscanf(t_string, "%d.%d.%d-%d:%d", + &ntm_time.tm_year, + &ntm_time.tm_mon, + &ntm_time.tm_mday, + &ntm_time.tm_hour, &ntm_time.tm_min) == 5) { + ntm_time.tm_year -= 1900; /* Adjust years */ + ntm_time.tm_mon -= 1; /* Adjust dates from 1-12 to 0-11 */ + *tm_time = ntm_time; + return (tm_time); + + } + + fprintf(stderr, invalid_date, "date", t_string); + + exit(FALSE); } -int -date_main(int argc, char * * argv) +int date_main(int argc, char **argv) { - char *date_str = NULL; - char *date_fmt = NULL; - char *t_buff; - int i; - int set_time = 0; - int rfc822 = 0; - int utc = 0; - int use_arg = 0; - time_t tm; - struct tm tm_time; - - /* Interpret command line args */ - i = --argc; - argv++; - while (i > 0 && **argv) { - if (**argv == '-') { - while (i>0 && *++(*argv)) switch (**argv) { - case 'R': - rfc822 = 1; - break; - case 's': - set_time = 1; - if(date_str != NULL) usage ( date_usage); - date_str = optarg; - break; - case 'u': - utc = 1; - if (putenv ("TZ=UTC0") != 0) { - fprintf(stderr, memory_exhausted, "date"); - exit( FALSE); + char *date_str = NULL; + char *date_fmt = NULL; + char *t_buff; + int i; + int set_time = 0; + int rfc822 = 0; + int utc = 0; + int use_arg = 0; + time_t tm; + struct tm tm_time; + + /* Interpret command line args */ + i = --argc; + argv++; + while (i > 0 && **argv) { + if (**argv == '-') { + while (i > 0 && *++(*argv)) + switch (**argv) { + case 'R': + rfc822 = 1; + break; + case 's': + set_time = 1; + if (date_str != NULL) + usage(date_usage); + date_str = optarg; + break; + case 'u': + utc = 1; + if (putenv("TZ=UTC0") != 0) { + fprintf(stderr, memory_exhausted, "date"); + exit(FALSE); + } + /* Look ma, no break. Don't fix it either. */ + case 'd': + use_arg = 1; + if (date_str != NULL) + usage(date_usage); + date_str = optarg; + break; + case '-': + usage(date_usage); + } + } else { + if ((date_fmt == NULL) && (strcmp(*argv, "+") == 0)) + date_fmt = *argv; + else if (date_str == NULL) { + set_time = 1; + date_str = *argv; + } else { + usage(date_usage); + } } - /* Look ma, no break. Don't fix it either. */ - case 'd': - use_arg = 1; - if(date_str != NULL) usage ( date_usage); - date_str = optarg; - break; - case '-': - usage ( date_usage); - } - } else { - if ( (date_fmt == NULL) && (strcmp(*argv, "+")==0) ) - date_fmt=*argv; - else if (date_str == NULL) { - set_time = 1; - date_str=*argv; - } else { - usage ( date_usage); - } + i--; + argv++; } - i--; - argv++; - } - - - /* Now we have parsed all the information except the date format - which depends on whether the clock is being set or read */ - - time(&tm); - memcpy(&tm_time, localtime(&tm), sizeof(tm_time)); - /* Zero out fields - take her back to midnight!*/ - if(date_str != NULL) { - tm_time.tm_sec = 0; - tm_time.tm_min = 0; - tm_time.tm_hour = 0; - } - - /* Process any date input to UNIX time since 1 Jan 1970 */ - if(date_str != NULL) { - - if(strchr(date_str, ':') != NULL) { - date_conv_ftime(&tm_time, date_str); - } else { - date_conv_time(&tm_time, date_str); - } - - /* Correct any day of week and day of year etc fields */ - tm = mktime(&tm_time); - if (tm < 0 ) { - fprintf(stderr, invalid_date, "date", date_str); - exit( FALSE); - } - - /* if setting time, set it */ - if(set_time) { - if( stime(&tm) < 0) { - fprintf(stderr, "date: can't set date.\n"); - exit( FALSE); - } - } - } - - /* Display output */ - - /* Deal with format string */ - if(date_fmt == NULL) { - date_fmt = (rfc822 - ? (utc - ? "%a, %_d %b %Y %H:%M:%S GMT" - : "%a, %_d %b %Y %H:%M:%S %z") - : "%a %b %e %H:%M:%S %Z %Y"); - - } else if ( *date_fmt == '\0' ) { - /* Imitate what GNU 'date' does with NO format string! */ - printf ("\n"); - exit( TRUE); - } - - /* Handle special conversions */ - - if( strncmp( date_fmt, "%f", 2) == 0 ) { - date_fmt = "%Y.%m.%d-%H:%M:%S"; - } - - /* Print OUTPUT (after ALL that!) */ - t_buff = malloc(201); - strftime(t_buff, 200, date_fmt, &tm_time); - printf("%s\n", t_buff); - - exit( TRUE); + + + /* Now we have parsed all the information except the date format + which depends on whether the clock is being set or read */ + + time(&tm); + memcpy(&tm_time, localtime(&tm), sizeof(tm_time)); + /* Zero out fields - take her back to midnight! */ + if (date_str != NULL) { + tm_time.tm_sec = 0; + tm_time.tm_min = 0; + tm_time.tm_hour = 0; + } + + /* Process any date input to UNIX time since 1 Jan 1970 */ + if (date_str != NULL) { + + if (strchr(date_str, ':') != NULL) { + date_conv_ftime(&tm_time, date_str); + } else { + date_conv_time(&tm_time, date_str); + } + + /* Correct any day of week and day of year etc fields */ + tm = mktime(&tm_time); + if (tm < 0) { + fprintf(stderr, invalid_date, "date", date_str); + exit(FALSE); + } + + /* if setting time, set it */ + if (set_time) { + if (stime(&tm) < 0) { + fprintf(stderr, "date: can't set date.\n"); + exit(FALSE); + } + } + } + + /* Display output */ + + /* Deal with format string */ + if (date_fmt == NULL) { + date_fmt = (rfc822 + ? (utc + ? "%a, %_d %b %Y %H:%M:%S GMT" + : "%a, %_d %b %Y %H:%M:%S %z") + : "%a %b %e %H:%M:%S %Z %Y"); + + } else if (*date_fmt == '\0') { + /* Imitate what GNU 'date' does with NO format string! */ + printf("\n"); + exit(TRUE); + } + + /* Handle special conversions */ + + if (strncmp(date_fmt, "%f", 2) == 0) { + date_fmt = "%Y.%m.%d-%H:%M:%S"; + } + + /* Print OUTPUT (after ALL that!) */ + t_buff = malloc(201); + strftime(t_buff, 200, date_fmt, &tm_time); + printf("%s\n", t_buff); + + exit(TRUE); } diff --git a/coreutils/dd.c b/coreutils/dd.c index 3e1024a60..0d5b3e8ab 100644 --- a/coreutils/dd.c +++ b/coreutils/dd.c @@ -1,3 +1,4 @@ +/* vi: set sw=4 ts=4: */ /* * Mini dd implementation for busybox * @@ -40,164 +41,159 @@ typedef unsigned long long int uintmax_t; #endif static const char dd_usage[] = -"dd [if=name] [of=name] [bs=n] [count=n] [skip=n] [seek=n]\n\n" -"Copy a file, converting and formatting according to options\n\n" -"\tif=FILE\tread from FILE instead of stdin\n" -"\tof=FILE\twrite to FILE instead of stdout\n" -"\tbs=n\tread and write n bytes at a time\n" -"\tcount=n\tcopy only n input blocks\n" -"\tskip=n\tskip n input blocks\n" -"\tseek=n\tskip n output blocks\n" -"\n" -"Numbers may be suffixed by w (x2), k (x1024), b (x512), or M (x1024^2)\n"; + "dd [if=name] [of=name] [bs=n] [count=n] [skip=n] [seek=n]\n\n" + "Copy a file, converting and formatting according to options\n\n" + "\tif=FILE\tread from FILE instead of stdin\n" + "\tof=FILE\twrite to FILE instead of stdout\n" + "\tbs=n\tread and write n bytes at a time\n" + "\tcount=n\tcopy only n input blocks\n" + "\tskip=n\tskip n input blocks\n" + "\tseek=n\tskip n output blocks\n" + "\n" + "Numbers may be suffixed by w (x2), k (x1024), b (x512), or M (x1024^2)\n"; -extern int dd_main (int argc, char **argv) + +extern int dd_main(int argc, char **argv) { - const char *inFile = NULL; - const char *outFile = NULL; - char *cp; - int inFd; - int outFd; - int inCc = 0; - int outCc; - long blockSize = 512; - uintmax_t skipBlocks = 0; - uintmax_t seekBlocks = 0; - uintmax_t count = (uintmax_t)-1; - uintmax_t intotal; - uintmax_t outTotal; - unsigned char *buf; - - argc--; - argv++; - - /* Parse any options */ - while (argc) { - if (inFile == NULL && (strncmp(*argv, "if", 2) == 0)) - inFile=((strchr(*argv, '='))+1); - else if (outFile == NULL && (strncmp(*argv, "of", 2) == 0)) - outFile=((strchr(*argv, '='))+1); - else if (strncmp("count", *argv, 5) == 0) { - count = getNum ((strchr(*argv, '='))+1); - if (count <= 0) { - fprintf (stderr, "Bad count value %s\n", *argv); - goto usage; - } - } - else if (strncmp(*argv, "bs", 2) == 0) { - blockSize = getNum ((strchr(*argv, '='))+1); - if (blockSize <= 0) { - fprintf (stderr, "Bad block size value %s\n", *argv); - goto usage; - } - } - else if (strncmp(*argv, "skip", 4) == 0) { - skipBlocks = getNum ((strchr(*argv, '='))+1); - if (skipBlocks <= 0) { - fprintf (stderr, "Bad skip value %s\n", *argv); - goto usage; - } + const char *inFile = NULL; + const char *outFile = NULL; + char *cp; + int inFd; + int outFd; + int inCc = 0; + int outCc; + long blockSize = 512; + uintmax_t skipBlocks = 0; + uintmax_t seekBlocks = 0; + uintmax_t count = (uintmax_t) - 1; + uintmax_t intotal; + uintmax_t outTotal; + unsigned char *buf; + + argc--; + argv++; + /* Parse any options */ + while (argc) { + if (inFile == NULL && (strncmp(*argv, "if", 2) == 0)) + inFile = ((strchr(*argv, '=')) + 1); + else if (outFile == NULL && (strncmp(*argv, "of", 2) == 0)) + outFile = ((strchr(*argv, '=')) + 1); + else if (strncmp("count", *argv, 5) == 0) { + count = getNum((strchr(*argv, '=')) + 1); + if (count <= 0) { + fprintf(stderr, "Bad count value %s\n", *argv); + goto usage; + } + } else if (strncmp(*argv, "bs", 2) == 0) { + blockSize = getNum((strchr(*argv, '=')) + 1); + if (blockSize <= 0) { + fprintf(stderr, "Bad block size value %s\n", *argv); + goto usage; + } + } else if (strncmp(*argv, "skip", 4) == 0) { + skipBlocks = getNum((strchr(*argv, '=')) + 1); + if (skipBlocks <= 0) { + fprintf(stderr, "Bad skip value %s\n", *argv); + goto usage; + } + + } else if (strncmp(*argv, "seek", 4) == 0) { + seekBlocks = getNum((strchr(*argv, '=')) + 1); + if (seekBlocks <= 0) { + fprintf(stderr, "Bad seek value %s\n", *argv); + goto usage; + } + + } else { + goto usage; + } + argc--; + argv++; } - else if (strncmp(*argv, "seek", 4) == 0) { - seekBlocks = getNum ((strchr(*argv, '='))+1); - if (seekBlocks <= 0) { - fprintf (stderr, "Bad seek value %s\n", *argv); - goto usage; - } + buf = malloc(blockSize); + if (buf == NULL) { + fprintf(stderr, "Cannot allocate buffer\n"); + exit(FALSE); } - else { - goto usage; + + intotal = 0; + outTotal = 0; + + if (inFile == NULL) + inFd = fileno(stdin); + else + inFd = open(inFile, 0); + + if (inFd < 0) { + perror(inFile); + free(buf); + exit(FALSE); } - argc--; - argv++; - } - - buf = malloc (blockSize); - if (buf == NULL) { - fprintf (stderr, "Cannot allocate buffer\n"); - exit( FALSE); - } - - intotal = 0; - outTotal = 0; - - if (inFile == NULL) - inFd = fileno(stdin); - else - inFd = open (inFile, 0); - - if (inFd < 0) { - perror (inFile); - free (buf); - exit( FALSE); - } - - if (outFile == NULL) - outFd = fileno(stdout); - else - outFd = open(outFile, O_WRONLY | O_CREAT | O_TRUNC, 0666); - - if (outFd < 0) { - perror (outFile); - close (inFd); - free (buf); - exit( FALSE); - } - - lseek(inFd, skipBlocks*blockSize, SEEK_SET); - lseek(outFd, seekBlocks*blockSize, SEEK_SET); - // - //TODO: Convert to using fullRead & fullWrite - // from utility.c - // -Erik - while (outTotal < count * blockSize) { - inCc = read (inFd, buf, blockSize); - if (inCc < 0) { - perror (inFile); - goto cleanup; - } else if (inCc == 0) { - goto cleanup; + + if (outFile == NULL) + outFd = fileno(stdout); + else + outFd = open(outFile, O_WRONLY | O_CREAT | O_TRUNC, 0666); + + if (outFd < 0) { + perror(outFile); + close(inFd); + free(buf); + exit(FALSE); } - intotal += inCc; - cp = buf; - - while (intotal > outTotal) { - if (outTotal + inCc > count * blockSize) - inCc = count * blockSize - outTotal; - outCc = write (outFd, cp, inCc); - if (outCc < 0) { - perror (outFile); - goto cleanup; - } else if (outCc == 0) { - goto cleanup; - } - - inCc -= outCc; - cp += outCc; - outTotal += outCc; + + lseek(inFd, skipBlocks * blockSize, SEEK_SET); + lseek(outFd, seekBlocks * blockSize, SEEK_SET); + // + //TODO: Convert to using fullRead & fullWrite + // from utility.c + // -Erik + while (outTotal < count * blockSize) { + inCc = read(inFd, buf, blockSize); + if (inCc < 0) { + perror(inFile); + goto cleanup; + } else if (inCc == 0) { + goto cleanup; + } + intotal += inCc; + cp = buf; + + while (intotal > outTotal) { + if (outTotal + inCc > count * blockSize) + inCc = count * blockSize - outTotal; + outCc = write(outFd, cp, inCc); + if (outCc < 0) { + perror(outFile); + goto cleanup; + } else if (outCc == 0) { + goto cleanup; + } + + inCc -= outCc; + cp += outCc; + outTotal += outCc; + } } - } - if (inCc < 0) - perror (inFile); + if (inCc < 0) + perror(inFile); cleanup: - close (inFd); - close (outFd); - free (buf); - - printf ("%ld+%d records in\n", (long)(intotal / blockSize), - (intotal % blockSize) != 0); - printf ("%ld+%d records out\n", (long)(outTotal / blockSize), - (outTotal % blockSize) != 0); - exit( TRUE); + close(inFd); + close(outFd); + free(buf); + + printf("%ld+%d records in\n", (long) (intotal / blockSize), + (intotal % blockSize) != 0); + printf("%ld+%d records out\n", (long) (outTotal / blockSize), + (outTotal % blockSize) != 0); + exit(TRUE); usage: - usage( dd_usage); + usage(dd_usage); } - - diff --git a/coreutils/df.c b/coreutils/df.c index 24c94a246..43d5d26e7 100644 --- a/coreutils/df.c +++ b/coreutils/df.c @@ -1,3 +1,4 @@ +/* vi: set sw=4 ts=4: */ /* * Mini df implementation for busybox * @@ -29,81 +30,81 @@ #include <fstab.h> static const char df_usage[] = "df [filesystem ...]\n" - "\n" "\tPrint the filesystem space used and space available.\n"; -extern const char mtab_file[]; /* Defined in utility.c */ + "\n" "\tPrint the filesystem space used and space available.\n"; + +extern const char mtab_file[]; /* Defined in utility.c */ static int df(char *device, const char *mountPoint) { - struct statfs s; - long blocks_used; - long blocks_percent_used; - struct fstab* fstabItem; - - if (statfs(mountPoint, &s) != 0) { - perror(mountPoint); - return FALSE; - } + struct statfs s; + long blocks_used; + long blocks_percent_used; + struct fstab *fstabItem; - if (s.f_blocks > 0) { - blocks_used = s.f_blocks - s.f_bfree; - blocks_percent_used = (long) - (blocks_used * 100.0 / (blocks_used + s.f_bavail) + 0.5); - /* Note that if /etc/fstab is missing, libc can't fix up /dev/root for us */ - if (strcmp (device, "/dev/root") == 0) { - fstabItem = getfsfile ("/"); - if (fstabItem != NULL) - device = fstabItem->fs_spec; + if (statfs(mountPoint, &s) != 0) { + perror(mountPoint); + return FALSE; } - printf("%-20s %9ld %9ld %9ld %3ld%% %s\n", - device, - (long) (s.f_blocks * (s.f_bsize / 1024.0)), - (long) ((s.f_blocks - s.f_bfree) * (s.f_bsize / 1024.0)), - (long) (s.f_bavail * (s.f_bsize / 1024.0)), - blocks_percent_used, mountPoint); - } + if (s.f_blocks > 0) { + blocks_used = s.f_blocks - s.f_bfree; + blocks_percent_used = (long) + (blocks_used * 100.0 / (blocks_used + s.f_bavail) + 0.5); + /* Note that if /etc/fstab is missing, libc can't fix up /dev/root for us */ + if (strcmp(device, "/dev/root") == 0) { + fstabItem = getfsfile("/"); + if (fstabItem != NULL) + device = fstabItem->fs_spec; + } + printf("%-20s %9ld %9ld %9ld %3ld%% %s\n", + device, + (long) (s.f_blocks * (s.f_bsize / 1024.0)), + (long) ((s.f_blocks - s.f_bfree) * (s.f_bsize / 1024.0)), + (long) (s.f_bavail * (s.f_bsize / 1024.0)), + blocks_percent_used, mountPoint); + + } - return TRUE; + return TRUE; } extern int df_main(int argc, char **argv) { - printf("%-20s %-14s %s %s %s %s\n", "Filesystem", - "1k-blocks", "Used", "Available", "Use%", "Mounted on"); + printf("%-20s %-14s %s %s %s %s\n", "Filesystem", + "1k-blocks", "Used", "Available", "Use%", "Mounted on"); - if (argc > 1) { - struct mntent *mountEntry; - int status; + if (argc > 1) { + struct mntent *mountEntry; + int status; - while (argc > 1) { - if ((mountEntry = findMountPoint(argv[1], mtab_file)) == - 0) { - fprintf(stderr, "%s: can't find mount point.\n", argv[1]); - exit( FALSE); - } - status = df(mountEntry->mnt_fsname, mountEntry->mnt_dir); - if (status != 0) - exit( status); - argc--; - argv++; - } - exit( TRUE); - } else { - FILE *mountTable; - struct mntent *mountEntry; + while (argc > 1) { + if ((mountEntry = findMountPoint(argv[1], mtab_file)) == 0) { + fprintf(stderr, "%s: can't find mount point.\n", argv[1]); + exit(FALSE); + } + status = df(mountEntry->mnt_fsname, mountEntry->mnt_dir); + if (status != 0) + exit(status); + argc--; + argv++; + } + exit(TRUE); + } else { + FILE *mountTable; + struct mntent *mountEntry; - mountTable = setmntent(mtab_file, "r"); - if (mountTable == 0) { - perror(mtab_file); - exit(FALSE); - } + mountTable = setmntent(mtab_file, "r"); + if (mountTable == 0) { + perror(mtab_file); + exit(FALSE); + } - while ((mountEntry = getmntent(mountTable))) { - df(mountEntry->mnt_fsname, mountEntry->mnt_dir); + while ((mountEntry = getmntent(mountTable))) { + df(mountEntry->mnt_fsname, mountEntry->mnt_dir); + } + endmntent(mountTable); } - endmntent(mountTable); - } - exit( TRUE); + exit(TRUE); } diff --git a/coreutils/du.c b/coreutils/du.c index e2cf3f7c0..7151e3a9c 100644 --- a/coreutils/du.c +++ b/coreutils/du.c @@ -1,3 +1,4 @@ +/* vi: set sw=4 ts=4: */ /* * Mini du implementation for busybox * @@ -31,119 +32,121 @@ #include <dirent.h> #include <stdio.h> #include <errno.h> -#include <sys/param.h> /* for PATH_MAX */ +#include <sys/param.h> /* for PATH_MAX */ -typedef void (Display)(long, char *); +typedef void (Display) (long, char *); static const char du_usage[] = -"du [OPTION]... [FILE]...\n\n" -"\t-s\tdisplay only a total for each argument\n" -; -static int du_depth = 0; + "du [OPTION]... [FILE]...\n\n" + "\t-s\tdisplay only a total for each argument\n"; -static Display *print; +static int du_depth = 0; -static void -print_normal(long size, char *filename) +static Display *print; + +static void print_normal(long size, char *filename) { - fprintf(stdout, "%-7ld %s\n", size, filename); + fprintf(stdout, "%-7ld %s\n", size, filename); } -static void -print_summary(long size, char *filename) +static void print_summary(long size, char *filename) { - if (du_depth == 1) { - print_normal(size, filename); - } + if (du_depth == 1) { + print_normal(size, filename); + } } /* tiny recursive du */ -static long -du(char *filename) +static long du(char *filename) { - struct stat statbuf; - long sum; - - if ((lstat(filename, &statbuf)) != 0) { - fprintf(stdout, "du: %s: %s\n", filename, strerror(errno)); - return 0; - } - - du_depth++; - sum = statbuf.st_blocks; - - if (S_ISDIR(statbuf.st_mode)) { - DIR *dir; - struct dirent *entry; - - dir = opendir(filename); - if (!dir) { return 0; } - while ((entry = readdir(dir))) { - char newfile[PATH_MAX + 1]; - char *name = entry->d_name; - - if ( (strcmp(name, "..") == 0) - || (strcmp(name, ".") == 0)) - { continue; } - - if (strlen(filename) + strlen(name) + 1 > PATH_MAX) { - fprintf(stderr, name_too_long, "du"); - return 0; - } - sprintf(newfile, "%s/%s", filename, name); - - sum += du(newfile); + struct stat statbuf; + long sum; + + if ((lstat(filename, &statbuf)) != 0) { + fprintf(stdout, "du: %s: %s\n", filename, strerror(errno)); + return 0; } - closedir(dir); - print(sum, filename); - } - du_depth--; - return sum; + + du_depth++; + sum = statbuf.st_blocks; + + if (S_ISDIR(statbuf.st_mode)) { + DIR *dir; + struct dirent *entry; + + dir = opendir(filename); + if (!dir) { + return 0; + } + while ((entry = readdir(dir))) { + char newfile[PATH_MAX + 1]; + char *name = entry->d_name; + + if ((strcmp(name, "..") == 0) + || (strcmp(name, ".") == 0)) { + continue; + } + + if (strlen(filename) + strlen(name) + 1 > PATH_MAX) { + fprintf(stderr, name_too_long, "du"); + return 0; + } + sprintf(newfile, "%s/%s", filename, name); + + sum += du(newfile); + } + closedir(dir); + print(sum, filename); + } + du_depth--; + return sum; } -int -du_main(int argc, char **argv) +int du_main(int argc, char **argv) { - int i; - char opt; - - /* default behaviour */ - print = print_normal; - - /* parse argv[] */ - for (i = 1; i < argc; i++) { - if (argv[i][0] == '-') { - opt = argv[i][1]; - switch (opt) { - case 's': - print = print_summary; - break; - case 'h': - usage(du_usage); - break; - default: - fprintf(stderr, "du: invalid option -- %c\n", opt); - usage(du_usage); - } - } else { - break; + int i; + char opt; + + /* default behaviour */ + print = print_normal; + + /* parse argv[] */ + for (i = 1; i < argc; i++) { + if (argv[i][0] == '-') { + opt = argv[i][1]; + switch (opt) { + case 's': + print = print_summary; + break; + case 'h': + usage(du_usage); + break; + default: + fprintf(stderr, "du: invalid option -- %c\n", opt); + usage(du_usage); + } + } else { + break; + } } - } - /* go through remaining args (if any) */ - if (i >= argc) { - du("."); - } else { - long sum; - for ( ; i < argc; i++) { - sum = du(argv[i]); - if ((sum) && (isDirectory(argv[i], FALSE))) { print_normal(sum, argv[i]); } + /* go through remaining args (if any) */ + if (i >= argc) { + du("."); + } else { + long sum; + + for (; i < argc; i++) { + sum = du(argv[i]); + if ((sum) && (isDirectory(argv[i], FALSE))) { + print_normal(sum, argv[i]); + } + } } - } - exit(0); + exit(0); } -/* $Id: du.c,v 1.10 2000/02/07 05:29:42 erik Exp $ */ +/* $Id: du.c,v 1.11 2000/02/08 19:58:47 erik Exp $ */ diff --git a/coreutils/head.c b/coreutils/head.c index b80d06580..82a73de2a 100644 --- a/coreutils/head.c +++ b/coreutils/head.c @@ -1,3 +1,4 @@ +/* vi: set sw=4 ts=4: */ /* * Mini head implementation for busybox * @@ -26,83 +27,86 @@ #include <stdio.h> const char head_usage[] = -"head [OPTION] [FILE]...\n\n" -"Print first 10 lines of each FILE to standard output.\n" -"With more than one FILE, precede each with a header giving the\n" -"file name. With no FILE, or when FILE is -, read standard input.\n\n" -"Options:\n" -"\t-n NUM\t\tPrint first NUM lines instead of first 10\n"; + "head [OPTION] [FILE]...\n\n" + "Print first 10 lines of each FILE to standard output.\n" + "With more than one FILE, precede each with a header giving the\n" + "file name. With no FILE, or when FILE is -, read standard input.\n\n" -int -head(int len, FILE *src) + "Options:\n" "\t-n NUM\t\tPrint first NUM lines instead of first 10\n"; + +int head(int len, FILE * src) { - int i; - char buffer[1024]; + int i; + char buffer[1024]; - for (i = 0; i < len; i++) { - fgets(buffer, 1024, src); - if (feof(src)) { break; } - fputs(buffer, stdout); - } - return 0; + for (i = 0; i < len; i++) { + fgets(buffer, 1024, src); + if (feof(src)) { + break; + } + fputs(buffer, stdout); + } + return 0; } /* BusyBoxed head(1) */ -int -head_main(int argc, char **argv) +int head_main(int argc, char **argv) { - char opt; - int len = 10, tmplen, i; + char opt; + int len = 10, tmplen, i; - /* parse argv[] */ - for (i = 1; i < argc; i++) { - if (argv[i][0] == '-') { - opt = argv[i][1]; - switch (opt) { - case 'n': - tmplen = 0; - if (++i < argc) - tmplen = atoi(argv[i]); - if (tmplen < 1) - usage(head_usage); - len = tmplen; - break; - case '-': - case 'h': - usage(head_usage); - default: - fprintf(stderr, "head: invalid option -- %c\n", opt); - usage(head_usage); - } - } else { - break; + /* parse argv[] */ + for (i = 1; i < argc; i++) { + if (argv[i][0] == '-') { + opt = argv[i][1]; + switch (opt) { + case 'n': + tmplen = 0; + if (++i < argc) + tmplen = atoi(argv[i]); + if (tmplen < 1) + usage(head_usage); + len = tmplen; + break; + case '-': + case 'h': + usage(head_usage); + default: + fprintf(stderr, "head: invalid option -- %c\n", opt); + usage(head_usage); + } + } else { + break; + } } - } - /* get rest of argv[] or stdin if nothing's left */ - if (i >= argc) { - head(len, stdin); + /* get rest of argv[] or stdin if nothing's left */ + if (i >= argc) { + head(len, stdin); - } else { - int need_headers = ((argc - i) > 1); - for ( ; i < argc; i++) { - FILE *src; - src = fopen(argv[i], "r"); - if (!src) { - fprintf(stderr,"head: %s: %s\n", argv[i], strerror(errno)); - } else { - /* emulating GNU behaviour */ - if (need_headers) { - fprintf(stdout, "==> %s <==\n", argv[i]); - } - head(len, src); - if (i < argc - 1) { - fprintf(stdout, "\n"); + } else { + int need_headers = ((argc - i) > 1); + + for (; i < argc; i++) { + FILE *src; + + src = fopen(argv[i], "r"); + if (!src) { + fprintf(stderr, "head: %s: %s\n", argv[i], + strerror(errno)); + } else { + /* emulating GNU behaviour */ + if (need_headers) { + fprintf(stdout, "==> %s <==\n", argv[i]); + } + head(len, src); + if (i < argc - 1) { + fprintf(stdout, "\n"); + } + } } - } } - } - exit(0); + exit(0); } -/* $Id: head.c,v 1.7 2000/02/07 05:29:42 erik Exp $ */ +/* $Id: head.c,v 1.8 2000/02/08 19:58:47 erik Exp $ */ diff --git a/coreutils/hostid.c b/coreutils/hostid.c index f8d5862ae..9e503e598 100644 --- a/coreutils/hostid.c +++ b/coreutils/hostid.c @@ -1,3 +1,4 @@ +/* vi: set sw=4 ts=4: */ /* * Mini hostid implementation for busybox * @@ -22,7 +23,8 @@ #include "internal.h" #include <stdio.h> -extern int hostid_main(int argc, char **argv) { - printf ("%lx\n", gethostid()); - exit( TRUE); +extern int hostid_main(int argc, char **argv) +{ + printf("%lx\n", gethostid()); + exit(TRUE); } diff --git a/coreutils/length.c b/coreutils/length.c index 2c83cdfd2..00e5a171b 100644 --- a/coreutils/length.c +++ b/coreutils/length.c @@ -1,14 +1,14 @@ +/* vi: set sw=4 ts=4: */ #include "internal.h" #include <stdlib.h> #include <string.h> #include <stdio.h> -extern int -length_main(int argc, char * * argv) +extern int length_main(int argc, char **argv) { - if ( argc != 2 || **(argv+1) == '-' ) { - usage("length string\n"); - } - printf("%d\n", strlen(argv[1])); - return( TRUE); + if (argc != 2 || **(argv + 1) == '-') { + usage("length string\n"); + } + printf("%d\n", strlen(argv[1])); + return (TRUE); } diff --git a/coreutils/ln.c b/coreutils/ln.c index f20b340ea..bc51cb0d5 100644 --- a/coreutils/ln.c +++ b/coreutils/ln.c @@ -1,3 +1,4 @@ +/* vi: set sw=4 ts=4: */ /* * Mini ln implementation for busybox * @@ -30,15 +31,16 @@ #include <stdio.h> #include <dirent.h> #include <errno.h> -#include <sys/param.h> /* for PATH_MAX */ +#include <sys/param.h> /* for PATH_MAX */ static const char ln_usage[] = - "ln [OPTION] TARGET... LINK_NAME|DIRECTORY\n\n" - "Create a link named LINK_NAME or DIRECTORY to the specified TARGET\n\n" - "Options:\n" - "\t-s\tmake symbolic links instead of hard links\n" - "\t-f\tremove existing destination files\n" - "\t-n\tno dereference symlinks - treat like normal file\n"; + "ln [OPTION] TARGET... LINK_NAME|DIRECTORY\n\n" + "Create a link named LINK_NAME or DIRECTORY to the specified TARGET\n\n" + "Options:\n" + "\t-s\tmake symbolic links instead of hard links\n" + + "\t-f\tremove existing destination files\n" + "\t-n\tno dereference symlinks - treat like normal file\n"; static int symlinkFlag = FALSE; static int removeoldFlag = FALSE; @@ -46,83 +48,83 @@ static int followLinks = TRUE; extern int ln_main(int argc, char **argv) { - char *linkName; - int linkIntoDirFlag; - - if (argc < 3) { - usage (ln_usage); - } - argc--; - argv++; - - /* Parse any options */ - while (**argv == '-') { - while (*++(*argv)) - switch (**argv) { - case 's': - symlinkFlag = TRUE; - break; - case 'f': - removeoldFlag = TRUE; - break; - case 'n': - followLinks = FALSE; - break; - default: - usage (ln_usage); - } + char *linkName; + int linkIntoDirFlag; + + if (argc < 3) { + usage(ln_usage); + } argc--; argv++; - } - - linkName = argv[argc - 1]; - - if (strlen(linkName) > PATH_MAX) { - fprintf(stderr, name_too_long, "ln"); - exit FALSE; - } - linkIntoDirFlag = isDirectory(linkName, TRUE); - - if ((argc > 3) && !linkIntoDirFlag) { - fprintf(stderr, not_a_directory, "ln", linkName); - exit FALSE; - } + /* Parse any options */ + while (**argv == '-') { + while (*++(*argv)) + switch (**argv) { + case 's': + symlinkFlag = TRUE; + break; + case 'f': + removeoldFlag = TRUE; + break; + case 'n': + followLinks = FALSE; + break; + default: + usage(ln_usage); + } + argc--; + argv++; + } - while (argc-- >= 2) { - char srcName[PATH_MAX + 1]; - int nChars, status; + linkName = argv[argc - 1]; - if (strlen(*argv) > PATH_MAX) { - fprintf(stderr, name_too_long, "ln"); - exit FALSE; + if (strlen(linkName) > PATH_MAX) { + fprintf(stderr, name_too_long, "ln"); + exit FALSE; } - if (followLinks == FALSE) { - strcpy(srcName, *argv); - } else { - /* Warning! This can silently truncate if > PATH_MAX, but - I don't think that there can be one > PATH_MAX anyway. */ - nChars = readlink(*argv, srcName, PATH_MAX); - srcName[nChars] = '\0'; - } + linkIntoDirFlag = isDirectory(linkName, TRUE); - if (removeoldFlag == TRUE) { - status = ( unlink(linkName) && errno != ENOENT ); - if (status != 0) { - perror(linkName); + if ((argc > 3) && !linkIntoDirFlag) { + fprintf(stderr, not_a_directory, "ln", linkName); exit FALSE; - } } - if (symlinkFlag == TRUE) - status = symlink(*argv, linkName); - else - status = link(*argv, linkName); - if (status != 0) { - perror(linkName); - exit FALSE; + while (argc-- >= 2) { + char srcName[PATH_MAX + 1]; + int nChars, status; + + if (strlen(*argv) > PATH_MAX) { + fprintf(stderr, name_too_long, "ln"); + exit FALSE; + } + + if (followLinks == FALSE) { + strcpy(srcName, *argv); + } else { + /* Warning! This can silently truncate if > PATH_MAX, but + I don't think that there can be one > PATH_MAX anyway. */ + nChars = readlink(*argv, srcName, PATH_MAX); + srcName[nChars] = '\0'; + } + + if (removeoldFlag == TRUE) { + status = (unlink(linkName) && errno != ENOENT); + if (status != 0) { + perror(linkName); + exit FALSE; + } + } + + if (symlinkFlag == TRUE) + status = symlink(*argv, linkName); + else + status = link(*argv, linkName); + if (status != 0) { + perror(linkName); + exit FALSE; + } } - } - exit TRUE; + exit TRUE; } diff --git a/coreutils/logname.c b/coreutils/logname.c index 5c8275ab4..182f40ed2 100644 --- a/coreutils/logname.c +++ b/coreutils/logname.c @@ -1,3 +1,4 @@ +/* vi: set sw=4 ts=4: */ /* * Mini logname implementation for busybox * @@ -23,18 +24,21 @@ #include <stdio.h> static const char logname_usage[] = "logname\n\n" -"Print the name of the current user.\n"; -extern int logname_main(int argc, char **argv) { + "Print the name of the current user.\n"; + +extern int logname_main(int argc, char **argv) +{ char *cp; - if (argc > 1) usage (logname_usage); + if (argc > 1) + usage(logname_usage); - cp = getlogin (); + cp = getlogin(); if (cp) { - puts (cp); - exit (TRUE); - } - fprintf (stderr, "%s: no login name\n", argv[0]); - exit (FALSE); + puts(cp); + exit(TRUE); + } + fprintf(stderr, "%s: no login name\n", argv[0]); + exit(FALSE); } diff --git a/coreutils/ls.c b/coreutils/ls.c index 450ea1814..f23c1e086 100644 --- a/coreutils/ls.c +++ b/coreutils/ls.c @@ -1,3 +1,4 @@ +/* vi: set sw=4 ts=4: */ /* * tiny-ls.c version 0.1.0: A minimalist 'ls' * Copyright (C) 1996 Brian Candler <B.Candler@pobox.com> @@ -40,18 +41,18 @@ * 1. requires lstat (BSD) - how do you do it without? */ -#define TERMINAL_WIDTH 80 /* use 79 if your terminal has linefold bug */ -#define COLUMN_WIDTH 14 /* default if AUTOWIDTH not defined */ -#define COLUMN_GAP 2 /* includes the file type char, if present */ +#define TERMINAL_WIDTH 80 /* use 79 if your terminal has linefold bug */ +#define COLUMN_WIDTH 14 /* default if AUTOWIDTH not defined */ +#define COLUMN_GAP 2 /* includes the file type char, if present */ #define HAS_REWINDDIR /************************************************************************/ #include "internal.h" #if !defined(__GLIBC__) && (__GLIBC__ >= 2) && (__GLIBC_MINOR__ >= 1) -# include <linux/types.h> +# include <linux/types.h> #else -# include <sys/types.h> +# include <sys/types.h> #endif #include <sys/stat.h> #include <stdio.h> @@ -75,28 +76,28 @@ #endif #define FMT_AUTO 0 -#define FMT_LONG 1 /* one record per line, extended info */ -#define FMT_SINGLE 2 /* one record per line */ -#define FMT_ROWS 3 /* print across rows */ -#define FMT_COLUMNS 3 /* fill columns (same, since we don't sort) */ +#define FMT_LONG 1 /* one record per line, extended info */ +#define FMT_SINGLE 2 /* one record per line */ +#define FMT_ROWS 3 /* print across rows */ +#define FMT_COLUMNS 3 /* fill columns (same, since we don't sort) */ #define TIME_MOD 0 #define TIME_CHANGE 1 #define TIME_ACCESS 2 -#define DISP_FTYPE 1 /* show character for file type */ -#define DISP_EXEC 2 /* show '*' if regular executable file */ -#define DISP_HIDDEN 4 /* show files starting . (except . and ..) */ -#define DISP_DOT 8 /* show . and .. */ -#define DISP_NUMERIC 16 /* numeric uid and gid */ -#define DISP_FULLTIME 32 /* show extended time display */ -#define DIR_NOLIST 64 /* show directory as itself, not contents */ -#define DISP_DIRNAME 128 /* show directory name (for internal use) */ -#define DIR_RECURSE 256 /* -R (not yet implemented) */ +#define DISP_FTYPE 1 /* show character for file type */ +#define DISP_EXEC 2 /* show '*' if regular executable file */ +#define DISP_HIDDEN 4 /* show files starting . (except . and ..) */ +#define DISP_DOT 8 /* show . and .. */ +#define DISP_NUMERIC 16 /* numeric uid and gid */ +#define DISP_FULLTIME 32 /* show extended time display */ +#define DIR_NOLIST 64 /* show directory as itself, not contents */ +#define DISP_DIRNAME 128 /* show directory name (for internal use) */ +#define DIR_RECURSE 256 /* -R (not yet implemented) */ -static unsigned char display_fmt = FMT_AUTO; -static unsigned short opts = 0; -static unsigned short column = 0; +static unsigned char display_fmt = FMT_AUTO; +static unsigned short opts = 0; +static unsigned short column = 0; #ifdef BB_FEATURE_AUTOWIDTH static unsigned short terminal_width = 0, column_width = 0; @@ -113,13 +114,14 @@ static unsigned char time_fmt = TIME_MOD; static void writenum(long val, short minwidth) { - char scratch[128]; + char scratch[128]; char *p = scratch + sizeof(scratch); short len = 0; short neg = (val < 0); - - if (neg) val = -val; + + if (neg) + val = -val; do *--p = (val % 10) + '0', len++, val /= 10; while (val); @@ -142,8 +144,9 @@ static void newline(void) static void tab(short col) { static const char spaces[] = " "; - #define nspaces ((sizeof spaces)-1) /* null terminator! */ - + +#define nspaces ((sizeof spaces)-1) /* null terminator! */ + short n = col - column; if (n > 0) { @@ -155,7 +158,7 @@ static void tab(short col) /* must be 1...(sizeof spaces) left */ wr(spaces, n); } - #undef nspaces +#undef nspaces } #ifdef BB_FEATURE_LS_FILETYPES @@ -163,8 +166,8 @@ static char append_char(mode_t mode) { if (!(opts & DISP_FTYPE)) return '\0'; - if ((opts & DISP_EXEC) && S_ISREG(mode) && (mode & (S_IXUSR|S_IXGRP|S_IXOTH))) - return '*'; + if ((opts & DISP_EXEC) && S_ISREG(mode) + && (mode & (S_IXUSR | S_IXGRP | S_IXOTH))) return '*'; return APPCHAR(mode); } #endif @@ -176,89 +179,93 @@ static char append_char(mode_t mode) ** **/ -static void list_single(const char *name, struct stat *info, const char *fullname) +static void list_single(const char *name, struct stat *info, + const char *fullname) { char scratch[PATH_MAX + 1]; short len = strlen(name); + #ifdef BB_FEATURE_LS_FILETYPES char append = append_char(info->st_mode); #endif - + if (display_fmt == FMT_LONG) { - mode_t mode = info->st_mode; + mode_t mode = info->st_mode; + newline(); wr(modeString(mode), 10); - column=10; - writenum((long)info->st_nlink,(short)5); + column = 10; + writenum((long) info->st_nlink, (short) 5); fputs(" ", stdout); #ifdef BB_FEATURE_LS_USERNAME if (!(opts & DISP_NUMERIC)) { - memset ( scratch, 0, sizeof (scratch)); - my_getpwuid( scratch, info->st_uid); + memset(scratch, 0, sizeof(scratch)); + my_getpwuid(scratch, info->st_uid); if (*scratch) { - fputs(scratch, stdout); - if ( strlen( scratch) <= 8 ) - wr(" ", 9-strlen( scratch)); - } - else { - writenum((long) info->st_uid,(short)8); + fputs(scratch, stdout); + if (strlen(scratch) <= 8) + wr(" ", 9 - strlen(scratch)); + } else { + writenum((long) info->st_uid, (short) 8); fputs(" ", stdout); } } else #endif { - writenum((long) info->st_uid,(short)8); - fputs(" ", stdout); + writenum((long) info->st_uid, (short) 8); + fputs(" ", stdout); } #ifdef BB_FEATURE_LS_USERNAME if (!(opts & DISP_NUMERIC)) { - memset ( scratch, 0, sizeof (scratch)); - my_getgrgid( scratch, info->st_gid); + memset(scratch, 0, sizeof(scratch)); + my_getgrgid(scratch, info->st_gid); if (*scratch) { - fputs(scratch, stdout); - if ( strlen( scratch) <= 8 ) - wr(" ", 8-strlen( scratch)); - } - else - writenum((long) info->st_gid,(short)8); + fputs(scratch, stdout); + if (strlen(scratch) <= 8) + wr(" ", 8 - strlen(scratch)); + } else + writenum((long) info->st_gid, (short) 8); } else #endif - writenum((long) info->st_gid,(short)8); + writenum((long) info->st_gid, (short) 8); //tab(26); if (S_ISBLK(mode) || S_ISCHR(mode)) { - writenum((long)MAJOR(info->st_rdev),(short)3); + writenum((long) MAJOR(info->st_rdev), (short) 3); fputs(", ", stdout); - writenum((long)MINOR(info->st_rdev),(short)3); - } - else - writenum((long)info->st_size,(short)8); + writenum((long) MINOR(info->st_rdev), (short) 3); + } else + writenum((long) info->st_size, (short) 8); fputs(" ", stdout); //tab(32); #ifdef BB_FEATURE_LS_TIMESTAMPS { time_t cal; char *string; - - switch(time_fmt) { + + switch (time_fmt) { case TIME_CHANGE: - cal=info->st_ctime; break; + cal = info->st_ctime; + break; case TIME_ACCESS: - cal=info->st_atime; break; + cal = info->st_atime; + break; default: - cal=info->st_mtime; break; + cal = info->st_mtime; + break; } - string=ctime(&cal); + string = ctime(&cal); if (opts & DISP_FULLTIME) - wr(string,24); + wr(string, 24); else { time_t age = time(NULL) - cal; - wr(string+4,7); /* mmm_dd_ */ - if(age < 3600L*24*365/2 && age > -15*60) + + wr(string + 4, 7); /* mmm_dd_ */ + if (age < 3600L * 24 * 365 / 2 && age > -15 * 60) /* hh:mm if less than 6 months old */ - wr(string+11,5); + wr(string + 11, 5); else /* _yyyy otherwise */ - wr(string+19,5); + wr(string + 19, 5); } wr(" ", 1); } @@ -269,7 +276,8 @@ static void list_single(const char *name, struct stat *info, const char *fullnam if (S_ISLNK(mode)) { wr(" -> ", 4); len = readlink(fullname, scratch, sizeof scratch); - if (len > 0) fwrite(scratch, 1, len, stdout); + if (len > 0) + fwrite(scratch, 1, len, stdout); #ifdef BB_FEATURE_LS_FILETYPES /* show type of destination */ if (opts & DISP_FTYPE) { @@ -287,18 +295,17 @@ static void list_single(const char *name, struct stat *info, const char *fullnam #endif } else { static short nexttab = 0; - + /* sort out column alignment */ - if (column == 0) - ; /* nothing to do */ + if (column == 0); /* nothing to do */ else if (display_fmt == FMT_SINGLE) newline(); else { if (nexttab + column_width > terminal_width #ifndef BB_FEATURE_AUTOWIDTH - || nexttab + len >= terminal_width + || nexttab + len >= terminal_width #endif - ) + ) newline(); else tab(nexttab); @@ -336,32 +343,33 @@ static int list_item(const char *name) struct stat info; DIR *dir; struct dirent *entry; - char fullname[MAXNAMLEN+1], *fnend; - + char fullname[MAXNAMLEN + 1], *fnend; + if (lstat(name, &info)) goto listerr; - - if (!S_ISDIR(info.st_mode) || - (opts & DIR_NOLIST)) { + + if (!S_ISDIR(info.st_mode) || (opts & DIR_NOLIST)) { list_single(name, &info, name); return 0; } /* Otherwise, it's a directory we want to list the contents of */ - if (opts & DISP_DIRNAME) { /* identify the directory */ + if (opts & DISP_DIRNAME) { /* identify the directory */ if (column) wr("\n\n", 2), column = 0; wr(name, strlen(name)); wr(":\n", 2); } - + dir = opendir(name); - if (!dir) goto listerr; + if (!dir) + goto listerr; #ifdef BB_FEATURE_AUTOWIDTH column_width = 0; while ((entry = readdir(dir)) != NULL) { short w = strlen(entry->d_name); + if (column_width < w) column_width = w; } @@ -370,39 +378,40 @@ static int list_item(const char *name) #else closedir(dir); dir = opendir(name); - if (!dir) goto listerr; + if (!dir) + goto listerr; #endif #endif /* List the contents */ - - strcpy(fullname,name); /* *** ignore '.' by itself */ - fnend=fullname+strlen(fullname); + + strcpy(fullname, name); /* *** ignore '.' by itself */ + fnend = fullname + strlen(fullname); if (fnend[-1] != '/') *fnend++ = '/'; - + while ((entry = readdir(dir)) != NULL) { - const char *en=entry->d_name; + const char *en = entry->d_name; + if (en[0] == '.') { - if (!en[1] || (en[1] == '.' && !en[2])) { /* . or .. */ + if (!en[1] || (en[1] == '.' && !en[2])) { /* . or .. */ if (!(opts & DISP_DOT)) continue; - } - else if (!(opts & DISP_HIDDEN)) + } else if (!(opts & DISP_HIDDEN)) continue; } /* FIXME: avoid stat if not required */ strcpy(fnend, entry->d_name); if (lstat(fullname, &info)) - goto direrr; /* (shouldn't fail) */ + goto direrr; /* (shouldn't fail) */ list_single(entry->d_name, &info, fullname); } closedir(dir); return 0; -direrr: - closedir(dir); -listerr: + direrr: + closedir(dir); + listerr: newline(); perror(name); return 1; @@ -432,50 +441,79 @@ static const char ls_usage[] = "ls [-1a" #endif "] [filenames...]\n"; -extern int -ls_main(int argc, char * * argv) +extern int ls_main(int argc, char **argv) { - int argi=1, i; - + int argi = 1, i; + /* process options */ while (argi < argc && argv[argi][0] == '-') { const char *p = &argv[argi][1]; - - if (!*p) goto print_usage_message; /* "-" by itself not allowed */ + + if (!*p) + goto print_usage_message; /* "-" by itself not allowed */ if (*p == '-') { - if (!p[1]) { /* "--" forces end of options */ + if (!p[1]) { /* "--" forces end of options */ argi++; break; } /* it's a long option name - we don't support them */ goto print_usage_message; } - + while (*p) switch (*p++) { - case 'l': display_fmt = FMT_LONG; break; - case '1': display_fmt = FMT_SINGLE; break; - case 'x': display_fmt = FMT_ROWS; break; - case 'C': display_fmt = FMT_COLUMNS; break; + case 'l': + display_fmt = FMT_LONG; + break; + case '1': + display_fmt = FMT_SINGLE; + break; + case 'x': + display_fmt = FMT_ROWS; + break; + case 'C': + display_fmt = FMT_COLUMNS; + break; #ifdef BB_FEATURE_LS_FILETYPES - case 'p': opts |= DISP_FTYPE; break; - case 'F': opts |= DISP_FTYPE|DISP_EXEC; break; + case 'p': + opts |= DISP_FTYPE; + break; + case 'F': + opts |= DISP_FTYPE | DISP_EXEC; + break; #endif - case 'A': opts |= DISP_HIDDEN; break; - case 'a': opts |= DISP_HIDDEN|DISP_DOT; break; - case 'n': opts |= DISP_NUMERIC; break; - case 'd': opts |= DIR_NOLIST; break; + case 'A': + opts |= DISP_HIDDEN; + break; + case 'a': + opts |= DISP_HIDDEN | DISP_DOT; + break; + case 'n': + opts |= DISP_NUMERIC; + break; + case 'd': + opts |= DIR_NOLIST; + break; #ifdef FEATURE_RECURSIVE - case 'R': opts |= DIR_RECURSE; break; + case 'R': + opts |= DIR_RECURSE; + break; #endif #ifdef BB_FEATURE_LS_TIMESTAMPS - case 'u': time_fmt = TIME_ACCESS; break; - case 'c': time_fmt = TIME_CHANGE; break; - case 'e': opts |= DISP_FULLTIME; break; + case 'u': + time_fmt = TIME_ACCESS; + break; + case 'c': + time_fmt = TIME_CHANGE; + break; + case 'e': + opts |= DISP_FULLTIME; + break; #endif - default: goto print_usage_message; + default: + goto print_usage_message; } - + argi++; } @@ -483,29 +521,30 @@ ls_main(int argc, char * * argv) if (display_fmt == FMT_AUTO) display_fmt = isatty(fileno(stdout)) ? FMT_COLUMNS : FMT_SINGLE; if (argi < argc - 1) - opts |= DISP_DIRNAME; /* 2 or more items? label directories */ + opts |= DISP_DIRNAME; /* 2 or more items? label directories */ #ifdef BB_FEATURE_AUTOWIDTH /* could add a -w option and/or TIOCGWINSZ call */ - if (terminal_width < 1) terminal_width = TERMINAL_WIDTH; - + if (terminal_width < 1) + terminal_width = TERMINAL_WIDTH; + for (i = argi; i < argc; i++) { int len = strlen(argv[i]); + if (column_width < len) column_width = len; } #endif /* process files specified, or current directory if none */ - i=0; + i = 0; if (argi == argc) i = list_item("."); while (argi < argc) i |= list_item(argv[argi++]); newline(); - exit( i); + exit(i); -print_usage_message: - usage (ls_usage); - exit( FALSE); + print_usage_message: + usage(ls_usage); + exit(FALSE); } - diff --git a/coreutils/mkdir.c b/coreutils/mkdir.c index 8e3f51bfb..70fdbdfb5 100644 --- a/coreutils/mkdir.c +++ b/coreutils/mkdir.c @@ -1,3 +1,4 @@ +/* vi: set sw=4 ts=4: */ /* * Mini mkdir implementation for busybox * @@ -28,14 +29,15 @@ #include <stdio.h> #include <errno.h> -#include <sys/param.h> /* for PATH_MAX */ +#include <sys/param.h> /* for PATH_MAX */ static const char mkdir_usage[] = -"mkdir [OPTION] DIRECTORY...\n\n" -"Create the DIRECTORY(ies), if they do not already exist\n\n" -"Options:\n" -"\t-m\tset permission mode (as in chmod), not rwxrwxrwx - umask\n" -"\t-p\tno error if existing, make parent directories as needed\n"; + "mkdir [OPTION] DIRECTORY...\n\n" + "Create the DIRECTORY(ies), if they do not already exist\n\n" + "Options:\n" + + "\t-m\tset permission mode (as in chmod), not rwxrwxrwx - umask\n" + "\t-p\tno error if existing, make parent directories as needed\n"; static int parentFlag = FALSE; @@ -44,71 +46,70 @@ static mode_t mode = 0777; extern int mkdir_main(int argc, char **argv) { - int i = FALSE; - argc--; - argv++; + int i = FALSE; - /* Parse any options */ - while (argc > 0 && **argv == '-') { - while (i == FALSE && *++(*argv)) { - switch (**argv) { - case 'm': - if (--argc == 0) - usage( mkdir_usage); - /* Find the specified modes */ - mode = 0; - if (parse_mode(*(++argv), &mode) == FALSE ) { - fprintf(stderr, "Unknown mode: %s\n", *argv); - exit FALSE; - } - /* Set the umask for this process so it doesn't - * screw up whatever the user just entered. */ - umask(0); - i = TRUE; - break; - case 'p': - parentFlag = TRUE; - break; - default: - usage( mkdir_usage); - } - } argc--; argv++; - } - - if (argc < 1) { - usage( mkdir_usage); - } - while (argc > 0) { - int status; - struct stat statBuf; - char buf[PATH_MAX + 1]; - if (strlen(*argv) > PATH_MAX - 1) { - fprintf(stderr, name_too_long, "mkdir"); - exit FALSE; - } - strcpy (buf, *argv); - status = stat(buf, &statBuf); - if (parentFlag == FALSE && status != -1 && errno != ENOENT) { - fprintf(stderr, "%s: File exists\n", buf); - exit FALSE; - } - if (parentFlag == TRUE) { - strcat( buf, "/"); - createPath(buf, mode); + /* Parse any options */ + while (argc > 0 && **argv == '-') { + while (i == FALSE && *++(*argv)) { + switch (**argv) { + case 'm': + if (--argc == 0) + usage(mkdir_usage); + /* Find the specified modes */ + mode = 0; + if (parse_mode(*(++argv), &mode) == FALSE) { + fprintf(stderr, "Unknown mode: %s\n", *argv); + exit FALSE; + } + /* Set the umask for this process so it doesn't + * screw up whatever the user just entered. */ + umask(0); + i = TRUE; + break; + case 'p': + parentFlag = TRUE; + break; + default: + usage(mkdir_usage); + } + } + argc--; + argv++; } - else { - if (mkdir (buf, mode) != 0 && parentFlag == FALSE) { - perror(buf); - exit FALSE; - } + + if (argc < 1) { + usage(mkdir_usage); } - argc--; - argv++; - } - exit TRUE; -} + while (argc > 0) { + int status; + struct stat statBuf; + char buf[PATH_MAX + 1]; + if (strlen(*argv) > PATH_MAX - 1) { + fprintf(stderr, name_too_long, "mkdir"); + exit FALSE; + } + strcpy(buf, *argv); + status = stat(buf, &statBuf); + if (parentFlag == FALSE && status != -1 && errno != ENOENT) { + fprintf(stderr, "%s: File exists\n", buf); + exit FALSE; + } + if (parentFlag == TRUE) { + strcat(buf, "/"); + createPath(buf, mode); + } else { + if (mkdir(buf, mode) != 0 && parentFlag == FALSE) { + perror(buf); + exit FALSE; + } + } + argc--; + argv++; + } + exit TRUE; +} diff --git a/coreutils/mkfifo.c b/coreutils/mkfifo.c index 676592ac7..c74402d4c 100644 --- a/coreutils/mkfifo.c +++ b/coreutils/mkfifo.c @@ -1,3 +1,4 @@ +/* vi: set sw=4 ts=4: */ /* * Mini mkfifo implementation for busybox * @@ -26,36 +27,43 @@ #include <errno.h> static const char mkfifo_usage[] = "mkfifo [OPTIONS] name\n\n" -"Create the named fifo\n\n" -"Options:\n" -"\t-m\tcreate the fifo with the specified mode; default = a=rw-umask\n"; + "Create the named fifo\n\n" + + "Options:\n" + "\t-m\tcreate the fifo with the specified mode; default = a=rw-umask\n"; extern int mkfifo_main(int argc, char **argv) { - char *thisarg; - mode_t mode = 0666; - argc--; - argv++; + char *thisarg; + mode_t mode = 0666; + + argc--; + argv++; - /* Parse any options */ - while (argc > 1) { - if (**argv != '-') usage(mkfifo_usage); - thisarg = *argv; thisarg++; - switch (*thisarg) { - case 'm': - argc--; argv++; - parse_mode(*argv, &mode); - break; - default: - usage (mkfifo_usage); - } - argc--; argv++; - } - if (argc < 1) usage (mkfifo_usage); - if (mkfifo(*argv, mode) < 0) { - perror("mkfifo"); - exit(255); - } else { - exit(TRUE); - } + /* Parse any options */ + while (argc > 1) { + if (**argv != '-') + usage(mkfifo_usage); + thisarg = *argv; + thisarg++; + switch (*thisarg) { + case 'm': + argc--; + argv++; + parse_mode(*argv, &mode); + break; + default: + usage(mkfifo_usage); + } + argc--; + argv++; + } + if (argc < 1) + usage(mkfifo_usage); + if (mkfifo(*argv, mode) < 0) { + perror("mkfifo"); + exit(255); + } else { + exit(TRUE); + } } diff --git a/coreutils/mknod.c b/coreutils/mknod.c index 5822cd3ad..b11a81f2a 100644 --- a/coreutils/mknod.c +++ b/coreutils/mknod.c @@ -1,3 +1,4 @@ +/* vi: set sw=4 ts=4: */ /* * Mini mknod implementation for busybox * @@ -28,22 +29,22 @@ #include <unistd.h> static const char mknod_usage[] = "mknod NAME TYPE MAJOR MINOR\n\n" -"Make block or character special files.\n\n" -"TYPEs include:\n" -"\tb:\tMake a block (buffered) device.\n" -"\tc or u:\tMake a character (un-buffered) device.\n" -"\tp:\tMake a named pipe. Major and minor are ignored for named pipes.\n"; + "Make block or character special files.\n\n" + "TYPEs include:\n" + "\tb:\tMake a block (buffered) device.\n" -int -mknod_main(int argc, char** argv) + "\tc or u:\tMake a character (un-buffered) device.\n" + "\tp:\tMake a named pipe. Major and minor are ignored for named pipes.\n"; + +int mknod_main(int argc, char **argv) { - mode_t mode = 0; - dev_t dev = 0; + mode_t mode = 0; + dev_t dev = 0; - if ( argc != 5 || **(argv+1) == '-' ) { - usage (mknod_usage); + if (argc != 5 || **(argv + 1) == '-') { + usage(mknod_usage); } - switch(argv[2][0]) { + switch (argv[2][0]) { case 'c': case 'u': mode = S_IFCHR; @@ -55,21 +56,21 @@ mknod_main(int argc, char** argv) mode = S_IFIFO; break; default: - usage (mknod_usage); + usage(mknod_usage); } - if ( mode == S_IFCHR || mode == S_IFBLK ) { + if (mode == S_IFCHR || mode == S_IFBLK) { dev = (atoi(argv[3]) << 8) | atoi(argv[4]); - if ( argc != 5 ) { - usage (mknod_usage); + if (argc != 5) { + usage(mknod_usage); } } mode |= 0666; - if ( mknod(argv[1], mode, dev) != 0 ) { + if (mknod(argv[1], mode, dev) != 0) { perror(argv[1]); - return( FALSE); + return (FALSE); } - return( TRUE); + return (TRUE); } diff --git a/coreutils/printf.c b/coreutils/printf.c index 5fd5ea303..41ab2e442 100644 --- a/coreutils/printf.c +++ b/coreutils/printf.c @@ -1,3 +1,4 @@ +/* vi: set sw=4 ts=4: */ /* printf - format and print data Copyright (C) 90, 91, 92, 93, 94, 95, 1996 Free Software Foundation, Inc. @@ -42,7 +43,7 @@ to convert all of the given arguments. David MacKenzie <djm@gnu.ai.mit.edu> */ - + // 19990508 Busy Boxed! Dave Cinege @@ -84,11 +85,11 @@ #if !defined(S_ISSOCK) && defined(S_IFSOCK) # define S_ISSOCK(m) (((m) & S_IFMT) == S_IFSOCK) #endif -#if !defined(S_ISMPB) && defined(S_IFMPB) /* V7 */ +#if !defined(S_ISMPB) && defined(S_IFMPB) /* V7 */ # define S_ISMPB(m) (((m) & S_IFMT) == S_IFMPB) # define S_ISMPC(m) (((m) & S_IFMT) == S_IFMPC) #endif -#if !defined(S_ISNWK) && defined(S_IFNWK) /* HP/UX */ +#if !defined(S_ISNWK) && defined(S_IFNWK) /* HP/UX */ # define S_ISNWK(m) (((m) & S_IFMT) == S_IFNWK) #endif @@ -121,407 +122,358 @@ #define hextobin(c) ((c)>='a'&&(c)<='f' ? (c)-'a'+10 : (c)>='A'&&(c)<='F' ? (c)-'A'+10 : (c)-'0') #define octtobin(c) ((c) - '0') -static double xstrtod __P ((char *s)); -static int print_esc __P ((char *escstart)); -static int print_formatted __P ((char *format, int argc, char **argv)); -static long xstrtol __P ((char *s)); -static unsigned long xstrtoul __P ((char *s)); -static void print_direc __P ((char *start, size_t length, int field_width, int precision, char *argument)); -static void print_esc_char __P ((int c)); -static void print_esc_string __P ((char *str)); -static void verify __P ((char *s, char *end)); +static double xstrtod __P((char *s)); +static int print_esc __P((char *escstart)); +static int print_formatted __P((char *format, int argc, char **argv)); +static long xstrtol __P((char *s)); +static unsigned long xstrtoul __P((char *s)); +static void print_direc +__P( + + (char *start, size_t length, int field_width, int precision, + char *argument)); +static void print_esc_char __P((int c)); +static void print_esc_string __P((char *str)); +static void verify __P((char *s, char *end)); /* The value to return to the calling program. */ static int exit_status; -static const char printf_usage[] = "printf format [argument...]\n"; +static const char printf_usage[] = "printf format [argument...]\n"; -int -printf_main(int argc, char** argv) +int printf_main(int argc, char **argv) { - char *format; - int args_used; - - exit_status = 0; - if ( argc <= 1 || **(argv+1) == '-' ) { - usage (printf_usage); - } - - format = argv[1]; - argc -= 2; - argv += 2; - - do - { - args_used = print_formatted (format, argc, argv); - argc -= args_used; - argv += args_used; - } - while (args_used > 0 && argc > 0); + char *format; + int args_used; + + exit_status = 0; + if (argc <= 1 || **(argv + 1) == '-') { + usage(printf_usage); + } + + format = argv[1]; + argc -= 2; + argv += 2; + + do { + args_used = print_formatted(format, argc, argv); + argc -= args_used; + argv += args_used; + } + while (args_used > 0 && argc > 0); /* if (argc > 0) fprintf(stderr, "excess args ignored"); */ - exit (exit_status); + exit(exit_status); } /* Print the text in FORMAT, using ARGV (with ARGC elements) for arguments to any `%' directives. Return the number of elements of ARGV used. */ -static int -print_formatted (char *format, int argc, char **argv) +static int print_formatted(char *format, int argc, char **argv) { - int save_argc = argc; /* Preserve original value. */ - char *f; /* Pointer into `format'. */ - char *direc_start; /* Start of % directive. */ - size_t direc_length; /* Length of % directive. */ - int field_width; /* Arg to first '*', or -1 if none. */ - int precision; /* Arg to second '*', or -1 if none. */ - - for (f = format; *f; ++f) - { - switch (*f) - { - case '%': - direc_start = f++; - direc_length = 1; - field_width = precision = -1; - if (*f == '%') - { - putchar ('%'); - break; - } - if (*f == 'b') - { - if (argc > 0) - { - print_esc_string (*argv); - ++argv; - --argc; - } - break; - } - if (strchr ("-+ #", *f)) - { - ++f; - ++direc_length; - } - if (*f == '*') - { - ++f; - ++direc_length; - if (argc > 0) - { - field_width = xstrtoul (*argv); - ++argv; - --argc; + int save_argc = argc; /* Preserve original value. */ + char *f; /* Pointer into `format'. */ + char *direc_start; /* Start of % directive. */ + size_t direc_length; /* Length of % directive. */ + int field_width; /* Arg to first '*', or -1 if none. */ + int precision; /* Arg to second '*', or -1 if none. */ + + for (f = format; *f; ++f) { + switch (*f) { + case '%': + direc_start = f++; + direc_length = 1; + field_width = precision = -1; + if (*f == '%') { + putchar('%'); + break; + } + if (*f == 'b') { + if (argc > 0) { + print_esc_string(*argv); + ++argv; + --argc; + } + break; + } + if (strchr("-+ #", *f)) { + ++f; + ++direc_length; + } + if (*f == '*') { + ++f; + ++direc_length; + if (argc > 0) { + field_width = xstrtoul(*argv); + ++argv; + --argc; + } else + field_width = 0; + } else + while (ISDIGIT(*f)) { + ++f; + ++direc_length; + } + if (*f == '.') { + ++f; + ++direc_length; + if (*f == '*') { + ++f; + ++direc_length; + if (argc > 0) { + precision = xstrtoul(*argv); + ++argv; + --argc; + } else + precision = 0; + } else + while (ISDIGIT(*f)) { + ++f; + ++direc_length; + } + } + if (*f == 'l' || *f == 'L' || *f == 'h') { + ++f; + ++direc_length; + } + /* + if (!strchr ("diouxXfeEgGcs", *f)) + fprintf(stderr, "%%%c: invalid directive", *f); + */ + ++direc_length; + if (argc > 0) { + print_direc(direc_start, direc_length, field_width, + precision, *argv); + ++argv; + --argc; + } else + print_direc(direc_start, direc_length, field_width, + precision, ""); + break; + + case '\\': + f += print_esc(f); + break; + + default: + putchar(*f); } - else - field_width = 0; - } - else - while (ISDIGIT (*f)) - { - ++f; - ++direc_length; - } - if (*f == '.') - { - ++f; - ++direc_length; - if (*f == '*') - { - ++f; - ++direc_length; - if (argc > 0) - { - precision = xstrtoul (*argv); - ++argv; - --argc; - } - else - precision = 0; - } - else - while (ISDIGIT (*f)) - { - ++f; - ++direc_length; - } - } - if (*f == 'l' || *f == 'L' || *f == 'h') - { - ++f; - ++direc_length; - } - /* - if (!strchr ("diouxXfeEgGcs", *f)) - fprintf(stderr, "%%%c: invalid directive", *f); - */ - ++direc_length; - if (argc > 0) - { - print_direc (direc_start, direc_length, field_width, - precision, *argv); - ++argv; - --argc; - } - else - print_direc (direc_start, direc_length, field_width, - precision, ""); - break; - - case '\\': - f += print_esc (f); - break; - - default: - putchar (*f); } - } - return save_argc - argc; + return save_argc - argc; } /* Print a \ escape sequence starting at ESCSTART. Return the number of characters in the escape sequence besides the backslash. */ -static int -print_esc (char *escstart) +static int print_esc(char *escstart) { - register char *p = escstart + 1; - int esc_value = 0; /* Value of \nnn escape. */ - int esc_length; /* Length of \nnn escape. */ - - /* \0ooo and \xhhh escapes have maximum length of 3 chars. */ - if (*p == 'x') - { - for (esc_length = 0, ++p; - esc_length < 3 && ISXDIGIT (*p); - ++esc_length, ++p) - esc_value = esc_value * 16 + hextobin (*p); + register char *p = escstart + 1; + int esc_value = 0; /* Value of \nnn escape. */ + int esc_length; /* Length of \nnn escape. */ + + /* \0ooo and \xhhh escapes have maximum length of 3 chars. */ + if (*p == 'x') { + for (esc_length = 0, ++p; + esc_length < 3 && ISXDIGIT(*p); ++esc_length, ++p) + esc_value = esc_value * 16 + hextobin(*p); /* if (esc_length == 0) fprintf(stderr, "missing hex in esc"); */ - putchar (esc_value); - } - else if (*p == '0') - { - for (esc_length = 0, ++p; - esc_length < 3 && isodigit (*p); - ++esc_length, ++p) - esc_value = esc_value * 8 + octtobin (*p); - putchar (esc_value); - } - else if (strchr ("\"\\abcfnrtv", *p)) - print_esc_char (*p++); + putchar(esc_value); + } else if (*p == '0') { + for (esc_length = 0, ++p; + esc_length < 3 && isodigit(*p); ++esc_length, ++p) + esc_value = esc_value * 8 + octtobin(*p); + putchar(esc_value); + } else if (strchr("\"\\abcfnrtv", *p)) + print_esc_char(*p++); /* else fprintf(stderr, "\\%c: invalid esc", *p); */ - return p - escstart - 1; + return p - escstart - 1; } /* Output a single-character \ escape. */ -static void -print_esc_char (int c) +static void print_esc_char(int c) { - switch (c) - { - case 'a': /* Alert. */ - putchar (7); - break; - case 'b': /* Backspace. */ - putchar (8); - break; - case 'c': /* Cancel the rest of the output. */ - exit (0); - break; - case 'f': /* Form feed. */ - putchar (12); - break; - case 'n': /* New line. */ - putchar (10); - break; - case 'r': /* Carriage return. */ - putchar (13); - break; - case 't': /* Horizontal tab. */ - putchar (9); - break; - case 'v': /* Vertical tab. */ - putchar (11); - break; - default: - putchar (c); - break; - } + switch (c) { + case 'a': /* Alert. */ + putchar(7); + break; + case 'b': /* Backspace. */ + putchar(8); + break; + case 'c': /* Cancel the rest of the output. */ + exit(0); + break; + case 'f': /* Form feed. */ + putchar(12); + break; + case 'n': /* New line. */ + putchar(10); + break; + case 'r': /* Carriage return. */ + putchar(13); + break; + case 't': /* Horizontal tab. */ + putchar(9); + break; + case 'v': /* Vertical tab. */ + putchar(11); + break; + default: + putchar(c); + break; + } } /* Print string STR, evaluating \ escapes. */ -static void -print_esc_string (char *str) +static void print_esc_string(char *str) { - for (; *str; str++) - if (*str == '\\') - str += print_esc (str); - else - putchar (*str); + for (; *str; str++) + if (*str == '\\') + str += print_esc(str); + else + putchar(*str); } static void -print_direc (char *start, size_t length, int field_width, int precision, char *argument) +print_direc(char *start, size_t length, int field_width, int precision, + char *argument) { - char *p; /* Null-terminated copy of % directive. */ - - p = xmalloc ((unsigned) (length + 1)); - strncpy (p, start, length); - p[length] = 0; - - switch (p[length - 1]) - { - case 'd': - case 'i': - if (field_width < 0) - { - if (precision < 0) - printf (p, xstrtol (argument)); - else - printf (p, precision, xstrtol (argument)); - } - else - { - if (precision < 0) - printf (p, field_width, xstrtol (argument)); - else - printf (p, field_width, precision, xstrtol (argument)); - } - break; - - case 'o': - case 'u': - case 'x': - case 'X': - if (field_width < 0) - { - if (precision < 0) - printf (p, xstrtoul (argument)); - else - printf (p, precision, xstrtoul (argument)); - } - else - { - if (precision < 0) - printf (p, field_width, xstrtoul (argument)); - else - printf (p, field_width, precision, xstrtoul (argument)); - } - break; - - case 'f': - case 'e': - case 'E': - case 'g': - case 'G': - if (field_width < 0) - { - if (precision < 0) - printf (p, xstrtod (argument)); - else - printf (p, precision, xstrtod (argument)); - } - else - { - if (precision < 0) - printf (p, field_width, xstrtod (argument)); - else - printf (p, field_width, precision, xstrtod (argument)); - } - break; - - case 'c': - printf (p, *argument); - break; - - case 's': - if (field_width < 0) - { - if (precision < 0) - printf (p, argument); - else - printf (p, precision, argument); - } - else - { - if (precision < 0) - printf (p, field_width, argument); - else - printf (p, field_width, precision, argument); + char *p; /* Null-terminated copy of % directive. */ + + p = xmalloc((unsigned) (length + 1)); + strncpy(p, start, length); + p[length] = 0; + + switch (p[length - 1]) { + case 'd': + case 'i': + if (field_width < 0) { + if (precision < 0) + printf(p, xstrtol(argument)); + else + printf(p, precision, xstrtol(argument)); + } else { + if (precision < 0) + printf(p, field_width, xstrtol(argument)); + else + printf(p, field_width, precision, xstrtol(argument)); + } + break; + + case 'o': + case 'u': + case 'x': + case 'X': + if (field_width < 0) { + if (precision < 0) + printf(p, xstrtoul(argument)); + else + printf(p, precision, xstrtoul(argument)); + } else { + if (precision < 0) + printf(p, field_width, xstrtoul(argument)); + else + printf(p, field_width, precision, xstrtoul(argument)); + } + break; + + case 'f': + case 'e': + case 'E': + case 'g': + case 'G': + if (field_width < 0) { + if (precision < 0) + printf(p, xstrtod(argument)); + else + printf(p, precision, xstrtod(argument)); + } else { + if (precision < 0) + printf(p, field_width, xstrtod(argument)); + else + printf(p, field_width, precision, xstrtod(argument)); + } + break; + + case 'c': + printf(p, *argument); + break; + + case 's': + if (field_width < 0) { + if (precision < 0) + printf(p, argument); + else + printf(p, precision, argument); + } else { + if (precision < 0) + printf(p, field_width, argument); + else + printf(p, field_width, precision, argument); + } + break; } - break; - } - free (p); + free(p); } -static unsigned long -xstrtoul (char *s) +static unsigned long xstrtoul(char *s) { - char *end; - unsigned long val; + char *end; + unsigned long val; - errno = 0; - val = strtoul (s, &end, 0); - verify (s, end); - return val; + errno = 0; + val = strtoul(s, &end, 0); + verify(s, end); + return val; } -static long -xstrtol (char *s) +static long xstrtol(char *s) { - char *end; - long val; + char *end; + long val; - errno = 0; - val = strtol (s, &end, 0); - verify (s, end); - return val; + errno = 0; + val = strtol(s, &end, 0); + verify(s, end); + return val; } -static double -xstrtod (char *s) +static double xstrtod(char *s) { - char *end; - double val; + char *end; + double val; - errno = 0; - val = strtod (s, &end); - verify (s, end); - return val; + errno = 0; + val = strtod(s, &end); + verify(s, end); + return val; } -static void -verify (char *s, char *end) +static void verify(char *s, char *end) { - if (errno) - { - fprintf(stderr, "%s", s); - exit_status = 1; - } - else if (*end) - { - /* - if (s == end) - fprintf(stderr, "%s: expected numeric", s); - else - fprintf(stderr, "%s: not completely converted", s); - */ - exit_status = 1; - } + if (errno) { + fprintf(stderr, "%s", s); + exit_status = 1; + } else if (*end) { + /* + if (s == end) + fprintf(stderr, "%s: expected numeric", s); + else + fprintf(stderr, "%s: not completely converted", s); + */ + exit_status = 1; + } } - diff --git a/coreutils/pwd.c b/coreutils/pwd.c index bacabd77a..00163178b 100644 --- a/coreutils/pwd.c +++ b/coreutils/pwd.c @@ -1,3 +1,4 @@ +/* vi: set sw=4 ts=4: */ /* * Mini pwd implementation for busybox * @@ -25,16 +26,15 @@ #include <dirent.h> #include <sys/param.h> -extern int -pwd_main(int argc, char * * argv) +extern int pwd_main(int argc, char **argv) { - char buf[PATH_MAX + 1]; + char buf[PATH_MAX + 1]; - if ( getcwd(buf, sizeof(buf)) == NULL ) { + if (getcwd(buf, sizeof(buf)) == NULL) { perror("get working directory"); - exit( FALSE); + exit(FALSE); } printf("%s\n", buf); - exit( TRUE); + exit(TRUE); } diff --git a/coreutils/rm.c b/coreutils/rm.c index ee434fb39..41afedaf9 100644 --- a/coreutils/rm.c +++ b/coreutils/rm.c @@ -1,3 +1,4 @@ +/* vi: set sw=4 ts=4: */ /* * Mini rm implementation for busybox * @@ -28,11 +29,12 @@ #include <dirent.h> #include <errno.h> -static const char* rm_usage = "rm [OPTION]... FILE...\n\n" -"Remove (unlink) the FILE(s).\n\n" -"Options:\n" -"\t-f\t\tremove existing destinations, never prompt\n" -"\t-r or -R\tremove the contents of directories recursively\n"; +static const char *rm_usage = "rm [OPTION]... FILE...\n\n" + "Remove (unlink) the FILE(s).\n\n" + "Options:\n" + + "\t-f\t\tremove existing destinations, never prompt\n" + "\t-r or -R\tremove the contents of directories recursively\n"; static int recursiveFlag = FALSE; @@ -40,63 +42,63 @@ static int forceFlag = FALSE; static const char *srcName; -static int fileAction(const char *fileName, struct stat* statbuf) +static int fileAction(const char *fileName, struct stat *statbuf) { - if (unlink( fileName) < 0 ) { - perror( fileName); - return ( FALSE); - } - return ( TRUE); + if (unlink(fileName) < 0) { + perror(fileName); + return (FALSE); + } + return (TRUE); } -static int dirAction(const char *fileName, struct stat* statbuf) +static int dirAction(const char *fileName, struct stat *statbuf) { - if (rmdir( fileName) < 0 ) { - perror( fileName); - return ( FALSE); - } - return ( TRUE); + if (rmdir(fileName) < 0) { + perror(fileName); + return (FALSE); + } + return (TRUE); } extern int rm_main(int argc, char **argv) { - struct stat statbuf; + struct stat statbuf; - if (argc < 2) { - usage( rm_usage); - } - argc--; - argv++; - - /* Parse any options */ - while (**argv == '-') { - while (*++(*argv)) - switch (**argv) { - case 'R': - case 'r': - recursiveFlag = TRUE; - break; - case 'f': - forceFlag = TRUE; - break; - default: - usage( rm_usage); - } + if (argc < 2) { + usage(rm_usage); + } argc--; argv++; - } - while (argc-- > 0) { - srcName = *(argv++); - if (forceFlag == TRUE && lstat(srcName, &statbuf) != 0 && errno == ENOENT) { - /* do not reports errors for non-existent files if -f, just skip them */ + /* Parse any options */ + while (**argv == '-') { + while (*++(*argv)) + switch (**argv) { + case 'R': + case 'r': + recursiveFlag = TRUE; + break; + case 'f': + forceFlag = TRUE; + break; + default: + usage(rm_usage); + } + argc--; + argv++; } - else { - if (recursiveAction( srcName, recursiveFlag, FALSE, - TRUE, fileAction, dirAction) == FALSE) { - exit( FALSE); - } + + while (argc-- > 0) { + srcName = *(argv++); + if (forceFlag == TRUE && lstat(srcName, &statbuf) != 0 + && errno == ENOENT) { + /* do not reports errors for non-existent files if -f, just skip them */ + } else { + if (recursiveAction(srcName, recursiveFlag, FALSE, + TRUE, fileAction, dirAction) == FALSE) { + exit(FALSE); + } + } } - } - exit( TRUE); + exit(TRUE); } diff --git a/coreutils/rmdir.c b/coreutils/rmdir.c index 013fef1a4..f49569749 100644 --- a/coreutils/rmdir.c +++ b/coreutils/rmdir.c @@ -1,3 +1,4 @@ +/* vi: set sw=4 ts=4: */ /* * Mini rmdir implementation for busybox * @@ -28,15 +29,16 @@ extern int rmdir_main(int argc, char **argv) { - if ( argc==1 || **(argv+1) == '-' ) { - usage( "rmdir [OPTION]... DIRECTORY...\n\nRemove the DIRECTORY(ies), if they are empty.\n"); - } + if (argc == 1 || **(argv + 1) == '-') { + usage + ("rmdir [OPTION]... DIRECTORY...\n\nRemove the DIRECTORY(ies), if they are empty.\n"); + } - while (--argc > 0) { - if ( rmdir(*(++argv)) == -1 ) { - fprintf(stderr, "%s: %s\n", *argv, strerror(errno)); - exit(FALSE); + while (--argc > 0) { + if (rmdir(*(++argv)) == -1) { + fprintf(stderr, "%s: %s\n", *argv, strerror(errno)); + exit(FALSE); + } } - } - exit(TRUE); + exit(TRUE); } diff --git a/coreutils/sleep.c b/coreutils/sleep.c index bfbb78f61..9687b8446 100644 --- a/coreutils/sleep.c +++ b/coreutils/sleep.c @@ -1,3 +1,4 @@ +/* vi: set sw=4 ts=4: */ /* * Mini sleep implementation for busybox * @@ -23,19 +24,17 @@ #include "internal.h" #include <stdio.h> -const char sleep_usage[] = "sleep N\n\n" -"Pause for N seconds.\n"; +const char sleep_usage[] = "sleep N\n\n" "Pause for N seconds.\n"; -extern int -sleep_main(int argc, char * * argv) +extern int sleep_main(int argc, char **argv) { - if ( (argc < 2) || (**(argv+1) == '-') ) { - usage( sleep_usage ); + if ((argc < 2) || (**(argv + 1) == '-')) { + usage(sleep_usage); } - if ( sleep(atoi(*(++argv))) != 0 ) { - perror( "sleep"); - exit (FALSE); + if (sleep(atoi(*(++argv))) != 0) { + perror("sleep"); + exit(FALSE); } else - exit (TRUE); + exit(TRUE); } diff --git a/coreutils/sort.c b/coreutils/sort.c index d529ce722..609c5e08c 100644 --- a/coreutils/sort.c +++ b/coreutils/sort.c @@ -1,3 +1,4 @@ +/* vi: set sw=4 ts=4: */ /* * Mini sort implementation for busybox * @@ -28,29 +29,27 @@ #include <stdio.h> #include <errno.h> -static const char sort_usage[] = -"sort [OPTION]... [FILE]...\n\n" -; +static const char sort_usage[] = "sort [OPTION]... [FILE]...\n\n"; /* typedefs _______________________________________________________________ */ /* line node */ typedef struct Line { - char *data; /* line data */ - struct Line *next; /* pointer to next line node */ + char *data; /* line data */ + struct Line *next; /* pointer to next line node */ } Line; /* singly-linked list of lines */ typedef struct { - int len; /* number of Lines */ - Line **sorted; /* array fed to qsort */ + int len; /* number of Lines */ + Line **sorted; /* array fed to qsort */ - Line *head; /* head of List */ - Line *current; /* current Line */ + Line *head; /* head of List */ + Line *current; /* current Line */ } List; /* comparison function */ -typedef int (Compare)(const void *, const void *); +typedef int (Compare) (const void *, const void *); /* methods ________________________________________________________________ */ @@ -58,175 +57,176 @@ typedef int (Compare)(const void *, const void *); static const int max = 1024; /* mallocate Line */ -static Line * -line_alloc() +static Line *line_alloc() { - Line *self; - self = malloc(1 * sizeof(Line)); - return self; + Line *self; + + self = malloc(1 * sizeof(Line)); + return self; } /* Initialize Line with string */ -static Line * -line_init(Line *self, const char *string) +static Line *line_init(Line * self, const char *string) { - self->data = malloc((strlen(string) + 1) * sizeof(char)); - if (self->data == NULL) { return NULL; } - strcpy(self->data, string); - self->next = NULL; - return self; + self->data = malloc((strlen(string) + 1) * sizeof(char)); + + if (self->data == NULL) { + return NULL; + } + strcpy(self->data, string); + self->next = NULL; + return self; } /* Construct Line from FILE* */ -static Line * -line_newFromFile(FILE *src) +static Line *line_newFromFile(FILE * src) { - char buffer[max]; - Line *self; - - if (fgets(buffer, max, src)) { - self = line_alloc(); - if (self == NULL) { return NULL; } - line_init(self, buffer); - return self; - } - return NULL; + char buffer[max]; + Line *self; + + if (fgets(buffer, max, src)) { + self = line_alloc(); + if (self == NULL) { + return NULL; + } + line_init(self, buffer); + return self; + } + return NULL; } /* Line destructor */ -static Line * -line_release(Line *self) +static Line *line_release(Line * self) { - if (self->data) { - free(self->data); - free(self); - } - return self; + if (self->data) { + free(self->data); + free(self); + } + return self; } /* Comparison */ /* ascii order */ -static int -compare_ascii(const void *a, const void *b) +static int compare_ascii(const void *a, const void *b) { - Line **doh; - Line *x, *y; + Line **doh; + Line *x, *y; - doh = (Line **) a; - x = *doh; - doh = (Line **) b; - y = *doh; + doh = (Line **) a; + x = *doh; + doh = (Line **) b; + y = *doh; - // fprintf(stdout, "> %p: %s< %p: %s", x, x->data, y, y->data); - return strcmp(x->data, y->data); + // fprintf(stdout, "> %p: %s< %p: %s", x, x->data, y, y->data); + return strcmp(x->data, y->data); } /* numeric order */ -static int -compare_numeric(const void *a, const void *b) +static int compare_numeric(const void *a, const void *b) { - Line **doh; - Line *x, *y; - int xint, yint; + Line **doh; + Line *x, *y; + int xint, yint; - doh = (Line **) a; - x = *doh; - doh = (Line **) b; - y = *doh; + doh = (Line **) a; + x = *doh; + doh = (Line **) b; + y = *doh; - xint = strtoul(x->data, NULL, 10); - yint = strtoul(y->data, NULL, 10); + xint = strtoul(x->data, NULL, 10); + yint = strtoul(y->data, NULL, 10); - return (xint - yint); + return (xint - yint); } /* List */ /* */ -static List * -list_init(List *self) +static List *list_init(List * self) { - self->len = 0; - self->sorted = NULL; - self->head = NULL; - self->current = NULL; - return self; + self->len = 0; + self->sorted = NULL; + self->head = NULL; + self->current = NULL; + return self; } /* for simplicity, the List gains ownership of the line */ -static List * -list_insert(List *self, Line *line) +static List *list_insert(List * self, Line * line) { - if (line == NULL) { return NULL; } - - /* first insertion */ - if (self->head == NULL) { - self->head = line; - self->current = line; - - /* all subsequent insertions */ - } else { - self->current->next = line; - self->current = line; - } - self->len++; - return self; + if (line == NULL) { + return NULL; + } + + /* first insertion */ + if (self->head == NULL) { + self->head = line; + self->current = line; + + /* all subsequent insertions */ + } else { + self->current->next = line; + self->current = line; + } + self->len++; + return self; } /* order the list according to compare() */ -static List * -list_sort(List *self, Compare *compare) +static List *list_sort(List * self, Compare * compare) { - int i; - Line *line; - - /* mallocate array of Line*s */ - self->sorted = (Line **) malloc(self->len * sizeof(Line*)); - if (self->sorted == NULL) { return NULL; } - - /* fill array w/ List's contents */ - i = 0; - line = self->head; - while (line) { - self->sorted[i++] = line; - line = line->next; - } - - /* apply qsort */ - qsort(self->sorted, self->len, sizeof(Line*), compare); - return self; + int i; + Line *line; + + /* mallocate array of Line*s */ + self->sorted = (Line **) malloc(self->len * sizeof(Line *)); + if (self->sorted == NULL) { + return NULL; + } + + /* fill array w/ List's contents */ + i = 0; + line = self->head; + while (line) { + self->sorted[i++] = line; + line = line->next; + } + + /* apply qsort */ + qsort(self->sorted, self->len, sizeof(Line *), compare); + return self; } /* precondition: list must be sorted */ -static List * -list_writeToFile(List *self, FILE* dst) +static List *list_writeToFile(List * self, FILE * dst) { - int i; - Line **line = self->sorted; - - if (self->sorted == NULL) { return NULL; } - for (i = 0; i < self->len; i++) { - fprintf(dst, "%s", line[i]->data); - } - return self; + int i; + Line **line = self->sorted; + + if (self->sorted == NULL) { + return NULL; + } + for (i = 0; i < self->len; i++) { + fprintf(dst, "%s", line[i]->data); + } + return self; } /* deallocate */ -static void -list_release(List *self) +static void list_release(List * self) { - Line *i; - Line *die; - - i = self->head; - while (i) { - die = i; - i = die->next; - line_release(die); - } + Line *i; + Line *die; + + i = self->head; + while (i) { + die = i; + i = die->next; + line_release(die); + } } @@ -237,76 +237,77 @@ list_release(List *self) * and finally print it */ -int -sort_main(int argc, char **argv) +int sort_main(int argc, char **argv) { - int i; - char opt; - List list; - Line *l; - Compare *compare; - - /* init */ - compare = compare_ascii; - list_init(&list); - - /* parse argv[] */ - for (i = 1; i < argc; i++) { - if (argv[i][0] == '-') { - opt = argv[i][1]; - switch (opt) { - case 'g': - /* what's the diff between -g && -n? */ - compare = compare_numeric; - break; - case 'h': - usage(sort_usage); - break; - case 'n': - /* what's the diff between -g && -n? */ - compare = compare_numeric; - break; - case 'r': - /* reverse */ - break; - default: - fprintf(stderr, "sort: invalid option -- %c\n", opt); - usage(sort_usage); - } - } else { - break; + int i; + char opt; + List list; + Line *l; + Compare *compare; + + /* init */ + compare = compare_ascii; + list_init(&list); + + /* parse argv[] */ + for (i = 1; i < argc; i++) { + if (argv[i][0] == '-') { + opt = argv[i][1]; + switch (opt) { + case 'g': + /* what's the diff between -g && -n? */ + compare = compare_numeric; + break; + case 'h': + usage(sort_usage); + break; + case 'n': + /* what's the diff between -g && -n? */ + compare = compare_numeric; + break; + case 'r': + /* reverse */ + break; + default: + fprintf(stderr, "sort: invalid option -- %c\n", opt); + usage(sort_usage); + } + } else { + break; + } } - } - /* this could be factored better */ + /* this could be factored better */ - /* work w/ stdin */ - if (i >= argc) { - while ( (l = line_newFromFile(stdin))) { - list_insert(&list, l); - } - list_sort(&list, compare); - list_writeToFile(&list, stdout); - list_release(&list); - - /* work w/ what's left in argv[] */ - } else { - FILE *src; - - for ( ; i < argc; i++) { - src = fopen(argv[i], "r"); - if (src == NULL) { break; } - while ( (l = line_newFromFile(src))) { - list_insert(&list, l); - } - fclose(src); + /* work w/ stdin */ + if (i >= argc) { + while ((l = line_newFromFile(stdin))) { + list_insert(&list, l); + } + list_sort(&list, compare); + list_writeToFile(&list, stdout); + list_release(&list); + + /* work w/ what's left in argv[] */ + } else { + FILE *src; + + for (; i < argc; i++) { + src = fopen(argv[i], "r"); + if (src == NULL) { + break; + } + while ((l = line_newFromFile(src))) { + list_insert(&list, l); + } + fclose(src); + } + list_sort(&list, compare); + list_writeToFile(&list, stdout); + list_release(&list); } - list_sort(&list, compare); - list_writeToFile(&list, stdout); - list_release(&list); - } - exit(0); + exit(0); } -/* $Id: sort.c,v 1.10 2000/02/07 05:29:42 erik Exp $ */ +/* $Id: sort.c,v 1.11 2000/02/08 19:58:47 erik Exp $ */ diff --git a/coreutils/sync.c b/coreutils/sync.c index 145ed1eda..f8160c8dc 100644 --- a/coreutils/sync.c +++ b/coreutils/sync.c @@ -1,3 +1,4 @@ +/* vi: set sw=4 ts=4: */ /* * Mini sync implementation for busybox * @@ -23,12 +24,10 @@ #include "internal.h" #include <stdio.h> -extern int -sync_main(int argc, char * * argv) +extern int sync_main(int argc, char **argv) { - if ( argc>1 && **(argv+1) == '-' ) { - usage( "sync\n\nWrite all buffered filesystem blocks to disk.\n"); - } - exit( sync()); + if (argc > 1 && **(argv + 1) == '-') { + usage("sync\n\nWrite all buffered filesystem blocks to disk.\n"); + } + exit(sync()); } - diff --git a/coreutils/tail.c b/coreutils/tail.c index 0ab8f11b0..31705afa2 100644 --- a/coreutils/tail.c +++ b/coreutils/tail.c @@ -1,3 +1,4 @@ +/* vi: set sw=4 ts=4: */ #include "internal.h" /* This file contains _two_ implementations of tail. One is * a bit more full featured, but costs 6k. The other (i.e. the @@ -68,22 +69,23 @@ static int forever; static int print_headers; const char tail_usage[] = - "tail [OPTION] [FILE]...\n\n" - "Print last 10 lines of each FILE to standard output.\n" - "With more than one FILE, precede each with a header giving the\n" - "file name. With no FILE, or when FILE is -, read standard input.\n\n" - "Options:\n" - "\t-n NUM\t\tPrint last NUM lines instead of first 10\n" - "\t-f\t\tOutput data as the file grows. This version\n" - "\t\t\tof 'tail -f' supports only one file at a time.\n"; + "tail [OPTION] [FILE]...\n\n" + "Print last 10 lines of each FILE to standard output.\n" + "With more than one FILE, precede each with a header giving the\n" + "file name. With no FILE, or when FILE is -, read standard input.\n\n" + "Options:\n" + "\t-n NUM\t\tPrint last NUM lines instead of first 10\n" + + "\t-f\t\tOutput data as the file grows. This version\n" + "\t\t\tof 'tail -f' supports only one file at a time.\n"; static void write_header(const char *filename) { - static int first_file = 1; + static int first_file = 1; - printf("%s==> %s <==\n", (first_file ? "" : "\n"), filename); - first_file = 0; + printf("%s==> %s <==\n", (first_file ? "" : "\n"), filename); + first_file = 0; } /* Print the last N_LINES lines from the end of file FD. @@ -97,57 +99,57 @@ static void write_header(const char *filename) static int file_lines(const char *filename, int fd, long int n_lines, off_t pos) { - char buffer[BUFSIZ]; - int bytes_read; - int i; /* Index into `buffer' for scanning. */ - - if (n_lines == 0) - return 0; + char buffer[BUFSIZ]; + int bytes_read; + int i; /* Index into `buffer' for scanning. */ - /* Set `bytes_read' to the size of the last, probably partial, buffer; - 0 < `bytes_read' <= `BUFSIZ'. */ - bytes_read = pos % BUFSIZ; - if (bytes_read == 0) - bytes_read = BUFSIZ; - /* Make `pos' a multiple of `BUFSIZ' (0 if the file is short), so that all - reads will be on block boundaries, which might increase efficiency. */ - pos -= bytes_read; - lseek(fd, pos, SEEK_SET); - bytes_read = fullRead(fd, buffer, bytes_read); - if (bytes_read == -1) - error("read error"); - - /* Count the incomplete line on files that don't end with a newline. */ - if (bytes_read && buffer[bytes_read - 1] != '\n') - --n_lines; - - do { - /* Scan backward, counting the newlines in this bufferfull. */ - for (i = bytes_read - 1; i >= 0; i--) { - /* Have we counted the requested number of newlines yet? */ - if (buffer[i] == '\n' && n_lines-- == 0) { - /* If this newline wasn't the last character in the buffer, - print the text after it. */ - if (i != bytes_read - 1) - XWRITE(STDOUT_FILENO, &buffer[i + 1], - bytes_read - (i + 1)); + if (n_lines == 0) return 0; - } - } - /* Not enough newlines in that bufferfull. */ - if (pos == 0) { - /* Not enough lines in the file; print the entire file. */ - lseek(fd, (off_t) 0, SEEK_SET); - return 0; - } - pos -= BUFSIZ; + + /* Set `bytes_read' to the size of the last, probably partial, buffer; + 0 < `bytes_read' <= `BUFSIZ'. */ + bytes_read = pos % BUFSIZ; + if (bytes_read == 0) + bytes_read = BUFSIZ; + /* Make `pos' a multiple of `BUFSIZ' (0 if the file is short), so that all + reads will be on block boundaries, which might increase efficiency. */ + pos -= bytes_read; lseek(fd, pos, SEEK_SET); - } - while ((bytes_read = fullRead(fd, buffer, BUFSIZ)) > 0); - if (bytes_read == -1) - error("read error"); + bytes_read = fullRead(fd, buffer, bytes_read); + if (bytes_read == -1) + error("read error"); + + /* Count the incomplete line on files that don't end with a newline. */ + if (bytes_read && buffer[bytes_read - 1] != '\n') + --n_lines; + + do { + /* Scan backward, counting the newlines in this bufferfull. */ + for (i = bytes_read - 1; i >= 0; i--) { + /* Have we counted the requested number of newlines yet? */ + if (buffer[i] == '\n' && n_lines-- == 0) { + /* If this newline wasn't the last character in the buffer, + print the text after it. */ + if (i != bytes_read - 1) + XWRITE(STDOUT_FILENO, &buffer[i + 1], + bytes_read - (i + 1)); + return 0; + } + } + /* Not enough newlines in that bufferfull. */ + if (pos == 0) { + /* Not enough lines in the file; print the entire file. */ + lseek(fd, (off_t) 0, SEEK_SET); + return 0; + } + pos -= BUFSIZ; + lseek(fd, pos, SEEK_SET); + } + while ((bytes_read = fullRead(fd, buffer, BUFSIZ)) > 0); + if (bytes_read == -1) + error("read error"); - return 0; + return 0; } /* Print the last N_LINES lines from the end of the standard input, @@ -157,100 +159,100 @@ file_lines(const char *filename, int fd, long int n_lines, off_t pos) static int pipe_lines(const char *filename, int fd, long int n_lines) { - struct linebuffer { - int nbytes, nlines; - char buffer[BUFSIZ]; - struct linebuffer *next; - }; - typedef struct linebuffer LBUFFER; - LBUFFER *first, *last, *tmp; - int i; /* Index into buffers. */ - int total_lines = 0; /* Total number of newlines in all buffers. */ - int errors = 0; - - first = last = (LBUFFER *) xmalloc(sizeof(LBUFFER)); - first->nbytes = first->nlines = 0; - first->next = NULL; - tmp = (LBUFFER *) xmalloc(sizeof(LBUFFER)); - - /* Input is always read into a fresh buffer. */ - while ((tmp->nbytes = fullRead(fd, tmp->buffer, BUFSIZ)) > 0) { - tmp->nlines = 0; - tmp->next = NULL; - - /* Count the number of newlines just read. */ - for (i = 0; i < tmp->nbytes; i++) - if (tmp->buffer[i] == '\n') - ++tmp->nlines; - total_lines += tmp->nlines; - - /* If there is enough room in the last buffer read, just append the new - one to it. This is because when reading from a pipe, `nbytes' can - often be very small. */ - if (tmp->nbytes + last->nbytes < BUFSIZ) { - memcpy(&last->buffer[last->nbytes], tmp->buffer, tmp->nbytes); - last->nbytes += tmp->nbytes; - last->nlines += tmp->nlines; - } else { - /* If there's not enough room, link the new buffer onto the end of - the list, then either free up the oldest buffer for the next - read if that would leave enough lines, or else malloc a new one. - Some compaction mechanism is possible but probably not - worthwhile. */ - last = last->next = tmp; - if (total_lines - first->nlines > n_lines) { - tmp = first; - total_lines -= first->nlines; - first = first->next; - } else - tmp = (LBUFFER *) xmalloc(sizeof(LBUFFER)); + struct linebuffer { + int nbytes, nlines; + char buffer[BUFSIZ]; + struct linebuffer *next; + }; + typedef struct linebuffer LBUFFER; + LBUFFER *first, *last, *tmp; + int i; /* Index into buffers. */ + int total_lines = 0; /* Total number of newlines in all buffers. */ + int errors = 0; + + first = last = (LBUFFER *) xmalloc(sizeof(LBUFFER)); + first->nbytes = first->nlines = 0; + first->next = NULL; + tmp = (LBUFFER *) xmalloc(sizeof(LBUFFER)); + + /* Input is always read into a fresh buffer. */ + while ((tmp->nbytes = fullRead(fd, tmp->buffer, BUFSIZ)) > 0) { + tmp->nlines = 0; + tmp->next = NULL; + + /* Count the number of newlines just read. */ + for (i = 0; i < tmp->nbytes; i++) + if (tmp->buffer[i] == '\n') + ++tmp->nlines; + total_lines += tmp->nlines; + + /* If there is enough room in the last buffer read, just append the new + one to it. This is because when reading from a pipe, `nbytes' can + often be very small. */ + if (tmp->nbytes + last->nbytes < BUFSIZ) { + memcpy(&last->buffer[last->nbytes], tmp->buffer, tmp->nbytes); + last->nbytes += tmp->nbytes; + last->nlines += tmp->nlines; + } else { + /* If there's not enough room, link the new buffer onto the end of + the list, then either free up the oldest buffer for the next + read if that would leave enough lines, or else malloc a new one. + Some compaction mechanism is possible but probably not + worthwhile. */ + last = last->next = tmp; + if (total_lines - first->nlines > n_lines) { + tmp = first; + total_lines -= first->nlines; + first = first->next; + } else + tmp = (LBUFFER *) xmalloc(sizeof(LBUFFER)); + } } - } - if (tmp->nbytes == -1) - error("read error"); - - free((char *) tmp); - - /* This prevents a core dump when the pipe contains no newlines. */ - if (n_lines == 0) - goto free_lbuffers; - - /* Count the incomplete line on files that don't end with a newline. */ - if (last->buffer[last->nbytes - 1] != '\n') { - ++last->nlines; - ++total_lines; - } - - /* Run through the list, printing lines. First, skip over unneeded - buffers. */ - for (tmp = first; total_lines - tmp->nlines > n_lines; tmp = tmp->next) - total_lines -= tmp->nlines; - - /* Find the correct beginning, then print the rest of the file. */ - if (total_lines > n_lines) { - char *cp; - - /* Skip `total_lines' - `n_lines' newlines. We made sure that - `total_lines' - `n_lines' <= `tmp->nlines'. */ - cp = tmp->buffer; - for (i = total_lines - n_lines; i; --i) - while (*cp++ != '\n') - /* Do nothing. */ ; - i = cp - tmp->buffer; - } else - i = 0; - XWRITE(STDOUT_FILENO, &tmp->buffer[i], tmp->nbytes - i); - - for (tmp = tmp->next; tmp; tmp = tmp->next) - XWRITE(STDOUT_FILENO, tmp->buffer, tmp->nbytes); + if (tmp->nbytes == -1) + error("read error"); + + free((char *) tmp); + + /* This prevents a core dump when the pipe contains no newlines. */ + if (n_lines == 0) + goto free_lbuffers; + + /* Count the incomplete line on files that don't end with a newline. */ + if (last->buffer[last->nbytes - 1] != '\n') { + ++last->nlines; + ++total_lines; + } + + /* Run through the list, printing lines. First, skip over unneeded + buffers. */ + for (tmp = first; total_lines - tmp->nlines > n_lines; tmp = tmp->next) + total_lines -= tmp->nlines; + + /* Find the correct beginning, then print the rest of the file. */ + if (total_lines > n_lines) { + char *cp; + + /* Skip `total_lines' - `n_lines' newlines. We made sure that + `total_lines' - `n_lines' <= `tmp->nlines'. */ + cp = tmp->buffer; + for (i = total_lines - n_lines; i; --i) + while (*cp++ != '\n') + /* Do nothing. */ ; + i = cp - tmp->buffer; + } else + i = 0; + XWRITE(STDOUT_FILENO, &tmp->buffer[i], tmp->nbytes - i); + + for (tmp = tmp->next; tmp; tmp = tmp->next) + XWRITE(STDOUT_FILENO, tmp->buffer, tmp->nbytes); free_lbuffers: - while (first) { - tmp = first->next; - free((char *) first); - first = tmp; - } - return errors; + while (first) { + tmp = first->next; + free((char *) first); + first = tmp; + } + return errors; } /* Display file FILENAME from the current position in FD to the end. @@ -259,25 +261,25 @@ static int pipe_lines(const char *filename, int fd, long int n_lines) static long dump_remainder(const char *filename, int fd) { - char buffer[BUFSIZ]; - int bytes_read; - long total; + char buffer[BUFSIZ]; + int bytes_read; + long total; - total = 0; + total = 0; output: - while ((bytes_read = fullRead(fd, buffer, BUFSIZ)) > 0) { - XWRITE(STDOUT_FILENO, buffer, bytes_read); - total += bytes_read; - } - if (bytes_read == -1) - error("read error"); - if (forever) { - fflush(stdout); - sleep(1); - goto output; - } - - return total; + while ((bytes_read = fullRead(fd, buffer, BUFSIZ)) > 0) { + XWRITE(STDOUT_FILENO, buffer, bytes_read); + total += bytes_read; + } + if (bytes_read == -1) + error("read error"); + if (forever) { + fflush(stdout); + sleep(1); + goto output; + } + + return total; } /* Output the last N_LINES lines of file FILENAME open for reading in FD. @@ -285,31 +287,31 @@ static long dump_remainder(const char *filename, int fd) static int tail_lines(const char *filename, int fd, long int n_lines) { - struct stat stats; - off_t length; - - if (print_headers) - write_header(filename); - - if (fstat(fd, &stats)) - error("fstat error"); - - /* Use file_lines only if FD refers to a regular file with - its file pointer positioned at beginning of file. */ - /* FIXME: adding the lseek conjunct is a kludge. - Once there's a reasonable test suite, fix the true culprit: - file_lines. file_lines shouldn't presume that the input - file pointer is initially positioned to beginning of file. */ - if (S_ISREG(stats.st_mode) - && lseek(fd, (off_t) 0, SEEK_CUR) == (off_t) 0) { - length = lseek(fd, (off_t) 0, SEEK_END); - if (length != 0 && file_lines(filename, fd, n_lines, length)) - return 1; - dump_remainder(filename, fd); - } else - return pipe_lines(filename, fd, n_lines); - - return 0; + struct stat stats; + off_t length; + + if (print_headers) + write_header(filename); + + if (fstat(fd, &stats)) + error("fstat error"); + + /* Use file_lines only if FD refers to a regular file with + its file pointer positioned at beginning of file. */ + /* FIXME: adding the lseek conjunct is a kludge. + Once there's a reasonable test suite, fix the true culprit: + file_lines. file_lines shouldn't presume that the input + file pointer is initially positioned to beginning of file. */ + if (S_ISREG(stats.st_mode) + && lseek(fd, (off_t) 0, SEEK_CUR) == (off_t) 0) { + length = lseek(fd, (off_t) 0, SEEK_END); + if (length != 0 && file_lines(filename, fd, n_lines, length)) + return 1; + dump_remainder(filename, fd); + } else + return pipe_lines(filename, fd, n_lines); + + return 0; } /* Display the last N_UNITS lines of file FILENAME. @@ -318,78 +320,78 @@ static int tail_lines(const char *filename, int fd, long int n_lines) static int tail_file(const char *filename, off_t n_units) { - int fd, errors; - - if (!strcmp(filename, "-")) { - filename = "standard input"; - errors = tail_lines(filename, 0, (long) n_units); - } else { - /* Not standard input. */ - fd = open(filename, O_RDONLY); - if (fd == -1) - error("open error"); - - errors = tail_lines(filename, fd, (long) n_units); - close(fd); - } - - return errors; + int fd, errors; + + if (!strcmp(filename, "-")) { + filename = "standard input"; + errors = tail_lines(filename, 0, (long) n_units); + } else { + /* Not standard input. */ + fd = open(filename, O_RDONLY); + if (fd == -1) + error("open error"); + + errors = tail_lines(filename, fd, (long) n_units); + close(fd); + } + + return errors; } extern int tail_main(int argc, char **argv) { - int exit_status = 0; - int n_units = DEFAULT_N_LINES; - int n_tmp, i; - char opt; - - forever = print_headers = 0; - - /* parse argv[] */ - for (i = 1; i < argc; i++) { - if (argv[i][0] == '-') { - opt = argv[i][1]; - switch (opt) { - case 'f': - forever = 1; - break; - case 'n': - n_tmp = 0; - if (++i < argc) - n_tmp = atoi(argv[i]); - if (n_tmp < 1) - usage(tail_usage); - n_units = n_tmp; - break; - case '-': - case 'h': - usage(tail_usage); - default: - fprintf(stderr, "tail: invalid option -- %c\n", opt); - usage(tail_usage); - } - } else { - break; + int exit_status = 0; + int n_units = DEFAULT_N_LINES; + int n_tmp, i; + char opt; + + forever = print_headers = 0; + + /* parse argv[] */ + for (i = 1; i < argc; i++) { + if (argv[i][0] == '-') { + opt = argv[i][1]; + switch (opt) { + case 'f': + forever = 1; + break; + case 'n': + n_tmp = 0; + if (++i < argc) + n_tmp = atoi(argv[i]); + if (n_tmp < 1) + usage(tail_usage); + n_units = n_tmp; + break; + case '-': + case 'h': + usage(tail_usage); + default: + fprintf(stderr, "tail: invalid option -- %c\n", opt); + usage(tail_usage); + } + } else { + break; + } } - } - if (i + 1 < argc) { - if (forever) { - fprintf(stderr, - "tail: option -f is invalid with multiple files\n"); - usage(tail_usage); + if (i + 1 < argc) { + if (forever) { + fprintf(stderr, + "tail: option -f is invalid with multiple files\n"); + usage(tail_usage); + } + print_headers = 1; } - print_headers = 1; - } - if (i >= argc) { - exit_status |= tail_file("-", n_units); - } else { - for (; i < argc; i++) - exit_status |= tail_file(argv[i], n_units); - } + if (i >= argc) { + exit_status |= tail_file("-", n_units); + } else { + for (; i < argc; i++) + exit_status |= tail_file(argv[i], n_units); + } - exit(exit_status == 0 ? EXIT_SUCCESS : EXIT_FAILURE); + exit(exit_status == 0 ? EXIT_SUCCESS : EXIT_FAILURE); } @@ -441,15 +443,15 @@ extern int tail_main(int argc, char **argv) #define NDEBUG 1 -static void detailed_error(int i, int errnum, char* fmt, ...) +static void detailed_error(int i, int errnum, char *fmt, ...) { - va_list arguments; + va_list arguments; - va_start(arguments, fmt); - vfprintf(stderr, fmt, arguments); - fprintf(stderr, "\n%s\n", strerror( errnum)); - va_end(arguments); - exit(i); + va_start(arguments, fmt); + vfprintf(stderr, fmt, arguments); + fprintf(stderr, "\n%s\n", strerror(errnum)); + va_end(arguments); + exit(i); } @@ -494,9 +496,8 @@ static int from_start; static int print_headers; /* When to print the filename banners. */ -enum header_mode -{ - multiple_files, always, never +enum header_mode { + multiple_files, always, never }; /* The name this program was run with. */ @@ -506,8 +507,7 @@ char *program_name; static int have_read_stdin; -static const char tail_usage[] = -"tail [OPTION]... [FILE]...\n\ +static const char tail_usage[] = "tail [OPTION]... [FILE]...\n\ \n\ Print last 10 lines of each FILE to standard output.\n\ With more than one FILE, precede each with a header giving the file name.\n\ @@ -524,15 +524,13 @@ If the first character of N (bytes or lines) is a `+', output begins with \n\ the Nth item from the start of each file, otherwise, print the last N items\n\ in the file. N bytes may be suffixed by k (x1024), b (x512), or m (1024^2).\n\n"; -static void -write_header (const char *filename, const char *comment) +static void write_header(const char *filename, const char *comment) { - static int first_file = 1; + static int first_file = 1; - printf ("%s==> %s%s%s <==\n", (first_file ? "" : "\n"), filename, - (comment ? ": " : ""), - (comment ? comment : "")); - first_file = 0; + printf("%s==> %s%s%s <==\n", (first_file ? "" : "\n"), filename, + (comment ? ": " : ""), (comment ? comment : "")); + first_file = 0; } /* Print the last N_LINES lines from the end of file FD. @@ -544,67 +542,62 @@ write_header (const char *filename, const char *comment) Return 0 if successful, 1 if an error occurred. */ static int -file_lines (const char *filename, int fd, long int n_lines, off_t pos) +file_lines(const char *filename, int fd, long int n_lines, off_t pos) { - char buffer[BUFSIZ]; - int bytes_read; - int i; /* Index into `buffer' for scanning. */ - - if (n_lines == 0) - return 0; - - /* Set `bytes_read' to the size of the last, probably partial, buffer; - 0 < `bytes_read' <= `BUFSIZ'. */ - bytes_read = pos % BUFSIZ; - if (bytes_read == 0) - bytes_read = BUFSIZ; - /* Make `pos' a multiple of `BUFSIZ' (0 if the file is short), so that all - reads will be on block boundaries, which might increase efficiency. */ - pos -= bytes_read; - lseek (fd, pos, SEEK_SET); - bytes_read = fullRead (fd, buffer, bytes_read); - if (bytes_read == -1) - { - detailed_error (0, errno, "%s", filename); - return 1; - } - - /* Count the incomplete line on files that don't end with a newline. */ - if (bytes_read && buffer[bytes_read - 1] != '\n') - --n_lines; - - do - { - /* Scan backward, counting the newlines in this bufferfull. */ - for (i = bytes_read - 1; i >= 0; i--) - { - /* Have we counted the requested number of newlines yet? */ - if (buffer[i] == '\n' && n_lines-- == 0) - { - /* If this newline wasn't the last character in the buffer, - print the text after it. */ - if (i != bytes_read - 1) - XWRITE (STDOUT_FILENO, &buffer[i + 1], bytes_read - (i + 1)); - return 0; - } + char buffer[BUFSIZ]; + int bytes_read; + int i; /* Index into `buffer' for scanning. */ + + if (n_lines == 0) + return 0; + + /* Set `bytes_read' to the size of the last, probably partial, buffer; + 0 < `bytes_read' <= `BUFSIZ'. */ + bytes_read = pos % BUFSIZ; + if (bytes_read == 0) + bytes_read = BUFSIZ; + /* Make `pos' a multiple of `BUFSIZ' (0 if the file is short), so that all + reads will be on block boundaries, which might increase efficiency. */ + pos -= bytes_read; + lseek(fd, pos, SEEK_SET); + bytes_read = fullRead(fd, buffer, bytes_read); + if (bytes_read == -1) { + detailed_error(0, errno, "%s", filename); + return 1; + } + + /* Count the incomplete line on files that don't end with a newline. */ + if (bytes_read && buffer[bytes_read - 1] != '\n') + --n_lines; + + do { + /* Scan backward, counting the newlines in this bufferfull. */ + for (i = bytes_read - 1; i >= 0; i--) { + /* Have we counted the requested number of newlines yet? */ + if (buffer[i] == '\n' && n_lines-- == 0) { + /* If this newline wasn't the last character in the buffer, + print the text after it. */ + if (i != bytes_read - 1) + XWRITE(STDOUT_FILENO, &buffer[i + 1], + bytes_read - (i + 1)); + return 0; + } + } + /* Not enough newlines in that bufferfull. */ + if (pos == 0) { + /* Not enough lines in the file; print the entire file. */ + lseek(fd, (off_t) 0, SEEK_SET); + return 0; + } + pos -= BUFSIZ; + lseek(fd, pos, SEEK_SET); } - /* Not enough newlines in that bufferfull. */ - if (pos == 0) - { - /* Not enough lines in the file; print the entire file. */ - lseek (fd, (off_t) 0, SEEK_SET); - return 0; + while ((bytes_read = fullRead(fd, buffer, BUFSIZ)) > 0); + if (bytes_read == -1) { + detailed_error(0, errno, "%s", filename); + return 1; } - pos -= BUFSIZ; - lseek (fd, pos, SEEK_SET); - } - while ((bytes_read = fullRead (fd, buffer, BUFSIZ)) > 0); - if (bytes_read == -1) - { - detailed_error (0, errno, "%s", filename); - return 1; - } - return 0; + return 0; } /* Print the last N_LINES lines from the end of the standard input, @@ -612,301 +605,264 @@ file_lines (const char *filename, int fd, long int n_lines, off_t pos) Buffer the text as a linked list of LBUFFERs, adding them as needed. Return 0 if successful, 1 if an error occured. */ -static int -pipe_lines (const char *filename, int fd, long int n_lines) +static int pipe_lines(const char *filename, int fd, long int n_lines) { - struct linebuffer - { - int nbytes, nlines; - char buffer[BUFSIZ]; - struct linebuffer *next; - }; - typedef struct linebuffer LBUFFER; - LBUFFER *first, *last, *tmp; - int i; /* Index into buffers. */ - int total_lines = 0; /* Total number of newlines in all buffers. */ - int errors = 0; - - first = last = (LBUFFER *) xmalloc (sizeof (LBUFFER)); - first->nbytes = first->nlines = 0; - first->next = NULL; - tmp = (LBUFFER *) xmalloc (sizeof (LBUFFER)); - - /* Input is always read into a fresh buffer. */ - while ((tmp->nbytes = fullRead (fd, tmp->buffer, BUFSIZ)) > 0) - { - tmp->nlines = 0; - tmp->next = NULL; - - /* Count the number of newlines just read. */ - for (i = 0; i < tmp->nbytes; i++) - if (tmp->buffer[i] == '\n') - ++tmp->nlines; - total_lines += tmp->nlines; - - /* If there is enough room in the last buffer read, just append the new - one to it. This is because when reading from a pipe, `nbytes' can - often be very small. */ - if (tmp->nbytes + last->nbytes < BUFSIZ) - { - memcpy (&last->buffer[last->nbytes], tmp->buffer, tmp->nbytes); - last->nbytes += tmp->nbytes; - last->nlines += tmp->nlines; + struct linebuffer { + int nbytes, nlines; + char buffer[BUFSIZ]; + struct linebuffer *next; + }; + typedef struct linebuffer LBUFFER; + LBUFFER *first, *last, *tmp; + int i; /* Index into buffers. */ + int total_lines = 0; /* Total number of newlines in all buffers. */ + int errors = 0; + + first = last = (LBUFFER *) xmalloc(sizeof(LBUFFER)); + first->nbytes = first->nlines = 0; + first->next = NULL; + tmp = (LBUFFER *) xmalloc(sizeof(LBUFFER)); + + /* Input is always read into a fresh buffer. */ + while ((tmp->nbytes = fullRead(fd, tmp->buffer, BUFSIZ)) > 0) { + tmp->nlines = 0; + tmp->next = NULL; + + /* Count the number of newlines just read. */ + for (i = 0; i < tmp->nbytes; i++) + if (tmp->buffer[i] == '\n') + ++tmp->nlines; + total_lines += tmp->nlines; + + /* If there is enough room in the last buffer read, just append the new + one to it. This is because when reading from a pipe, `nbytes' can + often be very small. */ + if (tmp->nbytes + last->nbytes < BUFSIZ) { + memcpy(&last->buffer[last->nbytes], tmp->buffer, tmp->nbytes); + last->nbytes += tmp->nbytes; + last->nlines += tmp->nlines; + } else { + /* If there's not enough room, link the new buffer onto the end of + the list, then either free up the oldest buffer for the next + read if that would leave enough lines, or else malloc a new one. + Some compaction mechanism is possible but probably not + worthwhile. */ + last = last->next = tmp; + if (total_lines - first->nlines > n_lines) { + tmp = first; + total_lines -= first->nlines; + first = first->next; + } else + tmp = (LBUFFER *) xmalloc(sizeof(LBUFFER)); + } + } + if (tmp->nbytes == -1) { + detailed_error(0, errno, "%s", filename); + errors = 1; + free((char *) tmp); + goto free_lbuffers; } - else - { - /* If there's not enough room, link the new buffer onto the end of - the list, then either free up the oldest buffer for the next - read if that would leave enough lines, or else malloc a new one. - Some compaction mechanism is possible but probably not - worthwhile. */ - last = last->next = tmp; - if (total_lines - first->nlines > n_lines) - { - tmp = first; - total_lines -= first->nlines; - first = first->next; - } - else - tmp = (LBUFFER *) xmalloc (sizeof (LBUFFER)); + + free((char *) tmp); + + /* This prevents a core dump when the pipe contains no newlines. */ + if (n_lines == 0) + goto free_lbuffers; + + /* Count the incomplete line on files that don't end with a newline. */ + if (last->buffer[last->nbytes - 1] != '\n') { + ++last->nlines; + ++total_lines; + } + + /* Run through the list, printing lines. First, skip over unneeded + buffers. */ + for (tmp = first; total_lines - tmp->nlines > n_lines; tmp = tmp->next) + total_lines -= tmp->nlines; + + /* Find the correct beginning, then print the rest of the file. */ + if (total_lines > n_lines) { + char *cp; + + /* Skip `total_lines' - `n_lines' newlines. We made sure that + `total_lines' - `n_lines' <= `tmp->nlines'. */ + cp = tmp->buffer; + for (i = total_lines - n_lines; i; --i) + while (*cp++ != '\n') + /* Do nothing. */ ; + i = cp - tmp->buffer; + } else + i = 0; + XWRITE(STDOUT_FILENO, &tmp->buffer[i], tmp->nbytes - i); + + for (tmp = tmp->next; tmp; tmp = tmp->next) + XWRITE(STDOUT_FILENO, tmp->buffer, tmp->nbytes); + + free_lbuffers: + while (first) { + tmp = first->next; + free((char *) first); + first = tmp; } - } - if (tmp->nbytes == -1) - { - detailed_error (0, errno, "%s", filename); - errors = 1; - free ((char *) tmp); - goto free_lbuffers; - } - - free ((char *) tmp); - - /* This prevents a core dump when the pipe contains no newlines. */ - if (n_lines == 0) - goto free_lbuffers; - - /* Count the incomplete line on files that don't end with a newline. */ - if (last->buffer[last->nbytes - 1] != '\n') - { - ++last->nlines; - ++total_lines; - } - - /* Run through the list, printing lines. First, skip over unneeded - buffers. */ - for (tmp = first; total_lines - tmp->nlines > n_lines; tmp = tmp->next) - total_lines -= tmp->nlines; - - /* Find the correct beginning, then print the rest of the file. */ - if (total_lines > n_lines) - { - char *cp; - - /* Skip `total_lines' - `n_lines' newlines. We made sure that - `total_lines' - `n_lines' <= `tmp->nlines'. */ - cp = tmp->buffer; - for (i = total_lines - n_lines; i; --i) - while (*cp++ != '\n') - /* Do nothing. */ ; - i = cp - tmp->buffer; - } - else - i = 0; - XWRITE (STDOUT_FILENO, &tmp->buffer[i], tmp->nbytes - i); - - for (tmp = tmp->next; tmp; tmp = tmp->next) - XWRITE (STDOUT_FILENO, tmp->buffer, tmp->nbytes); - -free_lbuffers: - while (first) - { - tmp = first->next; - free ((char *) first); - first = tmp; - } - return errors; + return errors; } /* Print the last N_BYTES characters from the end of pipe FD. This is a stripped down version of pipe_lines. Return 0 if successful, 1 if an error occurred. */ -static int -pipe_bytes (const char *filename, int fd, off_t n_bytes) +static int pipe_bytes(const char *filename, int fd, off_t n_bytes) { - struct charbuffer - { - int nbytes; - char buffer[BUFSIZ]; - struct charbuffer *next; - }; - typedef struct charbuffer CBUFFER; - CBUFFER *first, *last, *tmp; - int i; /* Index into buffers. */ - int total_bytes = 0; /* Total characters in all buffers. */ - int errors = 0; - - first = last = (CBUFFER *) xmalloc (sizeof (CBUFFER)); - first->nbytes = 0; - first->next = NULL; - tmp = (CBUFFER *) xmalloc (sizeof (CBUFFER)); - - /* Input is always read into a fresh buffer. */ - while ((tmp->nbytes = fullRead (fd, tmp->buffer, BUFSIZ)) > 0) - { - tmp->next = NULL; - - total_bytes += tmp->nbytes; - /* If there is enough room in the last buffer read, just append the new - one to it. This is because when reading from a pipe, `nbytes' can - often be very small. */ - if (tmp->nbytes + last->nbytes < BUFSIZ) - { - memcpy (&last->buffer[last->nbytes], tmp->buffer, tmp->nbytes); - last->nbytes += tmp->nbytes; + struct charbuffer { + int nbytes; + char buffer[BUFSIZ]; + struct charbuffer *next; + }; + typedef struct charbuffer CBUFFER; + CBUFFER *first, *last, *tmp; + int i; /* Index into buffers. */ + int total_bytes = 0; /* Total characters in all buffers. */ + int errors = 0; + + first = last = (CBUFFER *) xmalloc(sizeof(CBUFFER)); + first->nbytes = 0; + first->next = NULL; + tmp = (CBUFFER *) xmalloc(sizeof(CBUFFER)); + + /* Input is always read into a fresh buffer. */ + while ((tmp->nbytes = fullRead(fd, tmp->buffer, BUFSIZ)) > 0) { + tmp->next = NULL; + + total_bytes += tmp->nbytes; + /* If there is enough room in the last buffer read, just append the new + one to it. This is because when reading from a pipe, `nbytes' can + often be very small. */ + if (tmp->nbytes + last->nbytes < BUFSIZ) { + memcpy(&last->buffer[last->nbytes], tmp->buffer, tmp->nbytes); + last->nbytes += tmp->nbytes; + } else { + /* If there's not enough room, link the new buffer onto the end of + the list, then either free up the oldest buffer for the next + read if that would leave enough characters, or else malloc a new + one. Some compaction mechanism is possible but probably not + worthwhile. */ + last = last->next = tmp; + if (total_bytes - first->nbytes > n_bytes) { + tmp = first; + total_bytes -= first->nbytes; + first = first->next; + } else { + tmp = (CBUFFER *) xmalloc(sizeof(CBUFFER)); + } + } } - else - { - /* If there's not enough room, link the new buffer onto the end of - the list, then either free up the oldest buffer for the next - read if that would leave enough characters, or else malloc a new - one. Some compaction mechanism is possible but probably not - worthwhile. */ - last = last->next = tmp; - if (total_bytes - first->nbytes > n_bytes) - { - tmp = first; - total_bytes -= first->nbytes; - first = first->next; - } - else - { - tmp = (CBUFFER *) xmalloc (sizeof (CBUFFER)); - } + if (tmp->nbytes == -1) { + detailed_error(0, errno, "%s", filename); + errors = 1; + free((char *) tmp); + goto free_cbuffers; + } + + free((char *) tmp); + + /* Run through the list, printing characters. First, skip over unneeded + buffers. */ + for (tmp = first; total_bytes - tmp->nbytes > n_bytes; tmp = tmp->next) + total_bytes -= tmp->nbytes; + + /* Find the correct beginning, then print the rest of the file. + We made sure that `total_bytes' - `n_bytes' <= `tmp->nbytes'. */ + if (total_bytes > n_bytes) + i = total_bytes - n_bytes; + else + i = 0; + XWRITE(STDOUT_FILENO, &tmp->buffer[i], tmp->nbytes - i); + + for (tmp = tmp->next; tmp; tmp = tmp->next) + XWRITE(STDOUT_FILENO, tmp->buffer, tmp->nbytes); + + free_cbuffers: + while (first) { + tmp = first->next; + free((char *) first); + first = tmp; } - } - if (tmp->nbytes == -1) - { - detailed_error (0, errno, "%s", filename); - errors = 1; - free ((char *) tmp); - goto free_cbuffers; - } - - free ((char *) tmp); - - /* Run through the list, printing characters. First, skip over unneeded - buffers. */ - for (tmp = first; total_bytes - tmp->nbytes > n_bytes; tmp = tmp->next) - total_bytes -= tmp->nbytes; - - /* Find the correct beginning, then print the rest of the file. - We made sure that `total_bytes' - `n_bytes' <= `tmp->nbytes'. */ - if (total_bytes > n_bytes) - i = total_bytes - n_bytes; - else - i = 0; - XWRITE (STDOUT_FILENO, &tmp->buffer[i], tmp->nbytes - i); - - for (tmp = tmp->next; tmp; tmp = tmp->next) - XWRITE (STDOUT_FILENO, tmp->buffer, tmp->nbytes); - -free_cbuffers: - while (first) - { - tmp = first->next; - free ((char *) first); - first = tmp; - } - return errors; + return errors; } /* Skip N_BYTES characters from the start of pipe FD, and print any extra characters that were read beyond that. Return 1 on error, 0 if ok. */ -static int -start_bytes (const char *filename, int fd, off_t n_bytes) +static int start_bytes(const char *filename, int fd, off_t n_bytes) { - char buffer[BUFSIZ]; - int bytes_read = 0; - - while (n_bytes > 0 && (bytes_read = fullRead (fd, buffer, BUFSIZ)) > 0) - n_bytes -= bytes_read; - if (bytes_read == -1) - { - detailed_error (0, errno, "%s", filename); - return 1; - } - else if (n_bytes < 0) - XWRITE (STDOUT_FILENO, &buffer[bytes_read + n_bytes], -n_bytes); - return 0; + char buffer[BUFSIZ]; + int bytes_read = 0; + + while (n_bytes > 0 && (bytes_read = fullRead(fd, buffer, BUFSIZ)) > 0) + n_bytes -= bytes_read; + if (bytes_read == -1) { + detailed_error(0, errno, "%s", filename); + return 1; + } else if (n_bytes < 0) + XWRITE(STDOUT_FILENO, &buffer[bytes_read + n_bytes], -n_bytes); + return 0; } /* Skip N_LINES lines at the start of file or pipe FD, and print any extra characters that were read beyond that. Return 1 on error, 0 if ok. */ -static int -start_lines (const char *filename, int fd, long int n_lines) +static int start_lines(const char *filename, int fd, long int n_lines) { - char buffer[BUFSIZ]; - int bytes_read = 0; - int bytes_to_skip = 0; - - while (n_lines && (bytes_read = fullRead (fd, buffer, BUFSIZ)) > 0) - { - bytes_to_skip = 0; - while (bytes_to_skip < bytes_read) - if (buffer[bytes_to_skip++] == '\n' && --n_lines == 0) - break; - } - if (bytes_read == -1) - { - detailed_error (0, errno, "%s", filename); - return 1; - } - else if (bytes_to_skip < bytes_read) - { - XWRITE (STDOUT_FILENO, &buffer[bytes_to_skip], - bytes_read - bytes_to_skip); - } - return 0; + char buffer[BUFSIZ]; + int bytes_read = 0; + int bytes_to_skip = 0; + + while (n_lines && (bytes_read = fullRead(fd, buffer, BUFSIZ)) > 0) { + bytes_to_skip = 0; + while (bytes_to_skip < bytes_read) + if (buffer[bytes_to_skip++] == '\n' && --n_lines == 0) + break; + } + if (bytes_read == -1) { + detailed_error(0, errno, "%s", filename); + return 1; + } else if (bytes_to_skip < bytes_read) { + XWRITE(STDOUT_FILENO, &buffer[bytes_to_skip], + bytes_read - bytes_to_skip); + } + return 0; } /* Display file FILENAME from the current position in FD to the end. If `forever' is nonzero, keep reading from the end of the file until killed. Return the number of bytes read from the file. */ -static long -dump_remainder (const char *filename, int fd) +static long dump_remainder(const char *filename, int fd) { - char buffer[BUFSIZ]; - int bytes_read; - long total; - - total = 0; -output: - while ((bytes_read = fullRead (fd, buffer, BUFSIZ)) > 0) - { - XWRITE (STDOUT_FILENO, buffer, bytes_read); - total += bytes_read; - } - if (bytes_read == -1) - detailed_error (EXIT_FAILURE, errno, "%s", filename); - if (forever) - { - fflush (stdout); - sleep (1); - goto output; - } - else - { - if (forever_multiple) - fflush (stdout); - } - - return total; + char buffer[BUFSIZ]; + int bytes_read; + long total; + + total = 0; + output: + while ((bytes_read = fullRead(fd, buffer, BUFSIZ)) > 0) { + XWRITE(STDOUT_FILENO, buffer, bytes_read); + total += bytes_read; + } + if (bytes_read == -1) + detailed_error(EXIT_FAILURE, errno, "%s", filename); + if (forever) { + fflush(stdout); + sleep(1); + goto output; + } else { + if (forever_multiple) + fflush(stdout); + } + + return total; } /* Tail NFILES (>1) files forever until killed. The file names are in @@ -916,186 +872,161 @@ output: none of them have changed size in one iteration, we sleep for a second and try again. We do this until the user interrupts us. */ -static void -tail_forever (char **names, int nfiles) +static void tail_forever(char **names, int nfiles) { - int last; - - last = -1; - - while (1) - { - int i; - int changed; - - changed = 0; - for (i = 0; i < nfiles; i++) - { - struct stat stats; - - if (file_descs[i] < 0) - continue; - if (fstat (file_descs[i], &stats) < 0) - { - detailed_error (0, errno, "%s", names[i]); - file_descs[i] = -1; - continue; - } - if (stats.st_size == file_sizes[i]) - continue; - - /* This file has changed size. Print out what we can, and - then keep looping. */ - - changed = 1; - - if (stats.st_size < file_sizes[i]) - { - write_header (names[i], "file truncated"); - last = i; - lseek (file_descs[i], stats.st_size, SEEK_SET); - file_sizes[i] = stats.st_size; - continue; - } - - if (i != last) - { - if (print_headers) - write_header (names[i], NULL); - last = i; - } - file_sizes[i] += dump_remainder (names[i], file_descs[i]); - } + int last; + + last = -1; + + while (1) { + int i; + int changed; + + changed = 0; + for (i = 0; i < nfiles; i++) { + struct stat stats; + + if (file_descs[i] < 0) + continue; + if (fstat(file_descs[i], &stats) < 0) { + detailed_error(0, errno, "%s", names[i]); + file_descs[i] = -1; + continue; + } + if (stats.st_size == file_sizes[i]) + continue; + + /* This file has changed size. Print out what we can, and + then keep looping. */ + + changed = 1; + + if (stats.st_size < file_sizes[i]) { + write_header(names[i], "file truncated"); + last = i; + lseek(file_descs[i], stats.st_size, SEEK_SET); + file_sizes[i] = stats.st_size; + continue; + } + + if (i != last) { + if (print_headers) + write_header(names[i], NULL); + last = i; + } + file_sizes[i] += dump_remainder(names[i], file_descs[i]); + } - /* If none of the files changed size, sleep. */ - if (! changed) - sleep (1); - } + /* If none of the files changed size, sleep. */ + if (!changed) + sleep(1); + } } /* Output the last N_BYTES bytes of file FILENAME open for reading in FD. Return 0 if successful, 1 if an error occurred. */ -static int -tail_bytes (const char *filename, int fd, off_t n_bytes) +static int tail_bytes(const char *filename, int fd, off_t n_bytes) { - struct stat stats; - - /* FIXME: resolve this like in dd.c. */ - /* Use fstat instead of checking for errno == ESPIPE because - lseek doesn't work on some special files but doesn't return an - error, either. */ - if (fstat (fd, &stats)) - { - detailed_error (0, errno, "%s", filename); - return 1; - } - - if (from_start) - { - if (S_ISREG (stats.st_mode)) - lseek (fd, n_bytes, SEEK_CUR); - else if (start_bytes (filename, fd, n_bytes)) - return 1; - dump_remainder (filename, fd); - } - else - { - if (S_ISREG (stats.st_mode)) - { - off_t current_pos, end_pos; - size_t bytes_remaining; - - if ((current_pos = lseek (fd, (off_t) 0, SEEK_CUR)) != -1 - && (end_pos = lseek (fd, (off_t) 0, SEEK_END)) != -1) - { - off_t diff; - /* Be careful here. The current position may actually be - beyond the end of the file. */ - bytes_remaining = (diff = end_pos - current_pos) < 0 ? 0 : diff; - } - else - { - detailed_error (0, errno, "%s", filename); - return 1; - } - - if (bytes_remaining <= n_bytes) - { - /* From the current position to end of file, there are no - more bytes than have been requested. So reposition the - file pointer to the incoming current position and print - everything after that. */ - lseek (fd, current_pos, SEEK_SET); - } - else - { - /* There are more bytes remaining than were requested. - Back up. */ - lseek (fd, -n_bytes, SEEK_END); - } - dump_remainder (filename, fd); + struct stat stats; + + /* FIXME: resolve this like in dd.c. */ + /* Use fstat instead of checking for errno == ESPIPE because + lseek doesn't work on some special files but doesn't return an + error, either. */ + if (fstat(fd, &stats)) { + detailed_error(0, errno, "%s", filename); + return 1; + } + + if (from_start) { + if (S_ISREG(stats.st_mode)) + lseek(fd, n_bytes, SEEK_CUR); + else if (start_bytes(filename, fd, n_bytes)) + return 1; + dump_remainder(filename, fd); + } else { + if (S_ISREG(stats.st_mode)) { + off_t current_pos, end_pos; + size_t bytes_remaining; + + if ((current_pos = lseek(fd, (off_t) 0, SEEK_CUR)) != -1 + && (end_pos = lseek(fd, (off_t) 0, SEEK_END)) != -1) { + off_t diff; + + /* Be careful here. The current position may actually be + beyond the end of the file. */ + bytes_remaining = (diff = + end_pos - current_pos) < 0 ? 0 : diff; + } else { + detailed_error(0, errno, "%s", filename); + return 1; + } + + if (bytes_remaining <= n_bytes) { + /* From the current position to end of file, there are no + more bytes than have been requested. So reposition the + file pointer to the incoming current position and print + everything after that. */ + lseek(fd, current_pos, SEEK_SET); + } else { + /* There are more bytes remaining than were requested. + Back up. */ + lseek(fd, -n_bytes, SEEK_END); + } + dump_remainder(filename, fd); + } else + return pipe_bytes(filename, fd, n_bytes); } - else - return pipe_bytes (filename, fd, n_bytes); - } - return 0; + return 0; } /* Output the last N_LINES lines of file FILENAME open for reading in FD. Return 0 if successful, 1 if an error occurred. */ -static int -tail_lines (const char *filename, int fd, long int n_lines) +static int tail_lines(const char *filename, int fd, long int n_lines) { - struct stat stats; - off_t length; - - if (fstat (fd, &stats)) - { - detailed_error (0, errno, "%s", filename); - return 1; - } - - if (from_start) - { - if (start_lines (filename, fd, n_lines)) - return 1; - dump_remainder (filename, fd); - } - else - { - /* Use file_lines only if FD refers to a regular file with - its file pointer positioned at beginning of file. */ - /* FIXME: adding the lseek conjunct is a kludge. - Once there's a reasonable test suite, fix the true culprit: - file_lines. file_lines shouldn't presume that the input - file pointer is initially positioned to beginning of file. */ - if (S_ISREG (stats.st_mode) - && lseek (fd, (off_t) 0, SEEK_CUR) == (off_t) 0) - { - length = lseek (fd, (off_t) 0, SEEK_END); - if (length != 0 && file_lines (filename, fd, n_lines, length)) - return 1; - dump_remainder (filename, fd); + struct stat stats; + off_t length; + + if (fstat(fd, &stats)) { + detailed_error(0, errno, "%s", filename); + return 1; + } + + if (from_start) { + if (start_lines(filename, fd, n_lines)) + return 1; + dump_remainder(filename, fd); + } else { + /* Use file_lines only if FD refers to a regular file with + its file pointer positioned at beginning of file. */ + /* FIXME: adding the lseek conjunct is a kludge. + Once there's a reasonable test suite, fix the true culprit: + file_lines. file_lines shouldn't presume that the input + file pointer is initially positioned to beginning of file. */ + if (S_ISREG(stats.st_mode) + && lseek(fd, (off_t) 0, SEEK_CUR) == (off_t) 0) { + length = lseek(fd, (off_t) 0, SEEK_END); + if (length != 0 && file_lines(filename, fd, n_lines, length)) + return 1; + dump_remainder(filename, fd); + } else + return pipe_lines(filename, fd, n_lines); } - else - return pipe_lines (filename, fd, n_lines); - } - return 0; + return 0; } /* Display the last N_UNITS units of file FILENAME, open for reading in FD. Return 0 if successful, 1 if an error occurred. */ -static int -tail (const char *filename, int fd, off_t n_units) +static int tail(const char *filename, int fd, off_t n_units) { - if (count_lines) - return tail_lines (filename, fd, (long) n_units); - else - return tail_bytes (filename, fd, n_units); + if (count_lines) + return tail_lines(filename, fd, (long) n_units); + else + return tail_bytes(filename, fd, n_units); } /* Display the last N_UNITS units of file FILENAME. @@ -1103,207 +1034,183 @@ tail (const char *filename, int fd, off_t n_units) FILENUM is this file's index in the list of files the user gave. Return 0 if successful, 1 if an error occurred. */ -static int -tail_file (const char *filename, off_t n_units, int filenum) +static int tail_file(const char *filename, off_t n_units, int filenum) { - int fd, errors; - struct stat stats; - - if (!strcmp (filename, "-")) - { - have_read_stdin = 1; - filename = "standard input"; - if (print_headers) - write_header (filename, NULL); - errors = tail (filename, 0, n_units); - if (forever_multiple) - { - if (fstat (0, &stats) < 0) - { - detailed_error (0, errno, "standard input"); - errors = 1; - } - else if (!S_ISREG (stats.st_mode)) - { - detailed_error (0, 0, - "standard input: cannot follow end of non-regular file"); - errors = 1; - } - if (errors) - file_descs[filenum] = -1; - else - { - file_descs[filenum] = 0; - file_sizes[filenum] = stats.st_size; - } - } - } - else - { - /* Not standard input. */ - fd = open (filename, O_RDONLY); - if (fd == -1) - { - if (forever_multiple) - file_descs[filenum] = -1; - detailed_error (0, errno, "%s", filename); - errors = 1; - } - else - { - if (print_headers) - write_header (filename, NULL); - errors = tail (filename, fd, n_units); - if (forever_multiple) - { - if (fstat (fd, &stats) < 0) - { - detailed_error (0, errno, "%s", filename); - errors = 1; - } - else if (!S_ISREG (stats.st_mode)) - { - detailed_error (0, 0, "%s: cannot follow end of non-regular file", - filename); - errors = 1; - } - if (errors) - { - close (fd); - file_descs[filenum] = -1; - } - else - { - file_descs[filenum] = fd; - file_sizes[filenum] = stats.st_size; + int fd, errors; + struct stat stats; + + if (!strcmp(filename, "-")) { + have_read_stdin = 1; + filename = "standard input"; + if (print_headers) + write_header(filename, NULL); + errors = tail(filename, 0, n_units); + if (forever_multiple) { + if (fstat(0, &stats) < 0) { + detailed_error(0, errno, "standard input"); + errors = 1; + } else if (!S_ISREG(stats.st_mode)) { + detailed_error(0, 0, + "standard input: cannot follow end of non-regular file"); + errors = 1; + } + if (errors) + file_descs[filenum] = -1; + else { + file_descs[filenum] = 0; + file_sizes[filenum] = stats.st_size; + } } - } - else - { - if (close (fd)) - { - detailed_error (0, errno, "%s", filename); - errors = 1; + } else { + /* Not standard input. */ + fd = open(filename, O_RDONLY); + if (fd == -1) { + if (forever_multiple) + file_descs[filenum] = -1; + detailed_error(0, errno, "%s", filename); + errors = 1; + } else { + if (print_headers) + write_header(filename, NULL); + errors = tail(filename, fd, n_units); + if (forever_multiple) { + if (fstat(fd, &stats) < 0) { + detailed_error(0, errno, "%s", filename); + errors = 1; + } else if (!S_ISREG(stats.st_mode)) { + detailed_error(0, 0, + "%s: cannot follow end of non-regular file", + filename); + errors = 1; + } + if (errors) { + close(fd); + file_descs[filenum] = -1; + } else { + file_descs[filenum] = fd; + file_sizes[filenum] = stats.st_size; + } + } else { + if (close(fd)) { + detailed_error(0, errno, "%s", filename); + errors = 1; + } + } } - } } - } - return errors; + return errors; } -extern int -tail_main (int argc, char **argv) +extern int tail_main(int argc, char **argv) { - int stopit = 0; - enum header_mode header_mode = multiple_files; - int exit_status = 0; - /* If from_start, the number of items to skip before printing; otherwise, - the number of items at the end of the file to print. Initially, -1 - means the value has not been set. */ - off_t n_units = -1; - int n_files; - char **file; - - program_name = argv[0]; - have_read_stdin = 0; - count_lines = 1; - forever = forever_multiple = from_start = print_headers = 0; - - /* Parse any options */ - //fprintf(stderr, "argc=%d, argv=%s\n", argc, *argv); - while (--argc > 0 && ( **(++argv) == '-' || **argv == '+' )) { - if (**argv == '+') { - from_start = 1; + int stopit = 0; + enum header_mode header_mode = multiple_files; + int exit_status = 0; + + /* If from_start, the number of items to skip before printing; otherwise, + the number of items at the end of the file to print. Initially, -1 + means the value has not been set. */ + off_t n_units = -1; + int n_files; + char **file; + + program_name = argv[0]; + have_read_stdin = 0; + count_lines = 1; + forever = forever_multiple = from_start = print_headers = 0; + + /* Parse any options */ + //fprintf(stderr, "argc=%d, argv=%s\n", argc, *argv); + while (--argc > 0 && (**(++argv) == '-' || **argv == '+')) { + if (**argv == '+') { + from_start = 1; + } + stopit = 0; + while (stopit == 0 && *(++(*argv))) { + switch (**argv) { + case 'c': + count_lines = 0; + + if (--argc < 1) { + usage(tail_usage); + } + n_units = getNum(*(++argv)); + stopit = 1; + break; + + case 'f': + forever = 1; + break; + + case 'n': + count_lines = 1; + + if (--argc < 1) { + usage(tail_usage); + } + n_units = atol(*(++argv)); + stopit = 1; + break; + + case 'q': + header_mode = never; + break; + + case 'v': + header_mode = always; + break; + + default: + usage(tail_usage); + } + } + } + + + if (n_units == -1) + n_units = DEFAULT_N_LINES; + + /* To start printing with item N_UNITS from the start of the file, skip + N_UNITS - 1 items. `tail +0' is actually meaningless, but for Unix + compatibility it's treated the same as `tail +1'. */ + if (from_start) { + if (n_units) + --n_units; } - stopit = 0; - while (stopit == 0 && *(++(*argv))) { - switch (**argv) { - case 'c': - count_lines = 0; - - if (--argc < 1) { - usage(tail_usage); - } - n_units = getNum(*(++argv)); - stopit = 1; - break; - - case 'f': - forever = 1; - break; - - case 'n': - count_lines = 1; - - if (--argc < 1) { - usage(tail_usage); - } - n_units = atol(*(++argv)); - stopit = 1; - break; - - case 'q': - header_mode = never; - break; - - case 'v': - header_mode = always; - break; - - default: - usage (tail_usage); - } + + n_files = argc; + file = argv; + + if (n_files > 1 && forever) { + forever_multiple = 1; + forever = 0; + file_descs = (int *) xmalloc(n_files * sizeof(int)); + + file_sizes = (off_t *) xmalloc(n_files * sizeof(off_t)); } - } - - - if (n_units == -1) - n_units = DEFAULT_N_LINES; - - /* To start printing with item N_UNITS from the start of the file, skip - N_UNITS - 1 items. `tail +0' is actually meaningless, but for Unix - compatibility it's treated the same as `tail +1'. */ - if (from_start) - { - if (n_units) - --n_units; - } - - n_files = argc; - file = argv; - - if (n_files > 1 && forever) - { - forever_multiple = 1; - forever = 0; - file_descs = (int *) xmalloc (n_files * sizeof (int)); - file_sizes = (off_t *) xmalloc (n_files * sizeof (off_t)); - } - - if (header_mode == always - || (header_mode == multiple_files && n_files > 1)) - print_headers = 1; - - if (n_files == 0) - { - exit_status |= tail_file ("-", n_units, 0); - } - else - { - int i; - for (i = 0; i < n_files; i++) - exit_status |= tail_file (file[i], n_units, i); - - if (forever_multiple) - tail_forever (file, n_files); - } - - if (have_read_stdin && close (0) < 0) - detailed_error (EXIT_FAILURE, errno, "-"); - if (fclose (stdout) == EOF) - detailed_error (EXIT_FAILURE, errno, "write error"); - exit (exit_status == 0 ? EXIT_SUCCESS : EXIT_FAILURE); + + if (header_mode == always + || (header_mode == multiple_files && n_files > 1)) + print_headers = 1; + + if (n_files == 0) { + exit_status |= tail_file("-", n_units, 0); + } else { + int i; + + for (i = 0; i < n_files; i++) + exit_status |= tail_file(file[i], n_units, i); + + if (forever_multiple) + tail_forever(file, n_files); + } + + if (have_read_stdin && close(0) < 0) + detailed_error(EXIT_FAILURE, errno, "-"); + if (fclose(stdout) == EOF) + detailed_error(EXIT_FAILURE, errno, "write error"); + exit(exit_status == 0 ? EXIT_SUCCESS : EXIT_FAILURE); } diff --git a/coreutils/tee.c b/coreutils/tee.c index 4c5c691c6..2f746f96d 100644 --- a/coreutils/tee.c +++ b/coreutils/tee.c @@ -1,3 +1,4 @@ +/* vi: set sw=4 ts=4: */ /* * Mini tee implementation for busybox * @@ -25,102 +26,100 @@ #include <stdio.h> static const char tee_usage[] = - "tee [OPTION]... [FILE]...\n\n" - "Copy standard input to each FILE, and also to standard output.\n\n" - "Options:\n" - "\t-a\tappend to the given FILEs, do not overwrite\n" + "tee [OPTION]... [FILE]...\n\n" + "Copy standard input to each FILE, and also to standard output.\n\n" + "Options:\n" "\t-a\tappend to the given FILEs, do not overwrite\n" #if 0 - "\t-i\tignore interrupt signals\n" + "\t-i\tignore interrupt signals\n" #endif - ; +; /* FileList _______________________________________________________________ */ #define FL_MAX 1024 static FILE *FileList[FL_MAX]; -static int FL_end; +static int FL_end; + +typedef void (FL_Function) (FILE * file, char c); -typedef void (FL_Function)(FILE *file, char c); - /* apply a function to everything in FileList */ -static void -FL_apply(FL_Function *f, char c) +static void FL_apply(FL_Function * f, char c) { - int i; - for (i = 0; i <= FL_end; i++) { - f(FileList[i], c); - } + int i; + + for (i = 0; i <= FL_end; i++) { + f(FileList[i], c); + } } /* FL_Function for writing to files*/ -static void -tee_fwrite(FILE *file, char c) +static void tee_fwrite(FILE * file, char c) { - fputc(c, file); + fputc(c, file); } /* FL_Function for closing files */ -static void -tee_fclose(FILE *file, char c) +static void tee_fclose(FILE * file, char c) { - fclose(file); + fclose(file); } /* ________________________________________________________________________ */ /* BusyBoxed tee(1) */ -int -tee_main(int argc, char **argv) +int tee_main(int argc, char **argv) { - int i; - char c; - char opt; - char opt_fopen[2] = "w"; - FILE *file; - - /* parse argv[] */ - for (i = 1; i < argc; i++) { - if (argv[i][0] == '-') { - opt = argv[i][1]; - switch (opt) { - case 'a': - opt_fopen[0] = 'a'; - break; + int i; + char c; + char opt; + char opt_fopen[2] = "w"; + FILE *file; + + /* parse argv[] */ + for (i = 1; i < argc; i++) { + if (argv[i][0] == '-') { + opt = argv[i][1]; + switch (opt) { + case 'a': + opt_fopen[0] = 'a'; + break; #if 0 - case 'i': - fprintf(stderr, "ignore interrupt not implemented\n"); - break; + case 'i': + fprintf(stderr, "ignore interrupt not implemented\n"); + break; #endif - default: - usage(tee_usage); - } - } else { - break; + default: + usage(tee_usage); + } + } else { + break; + } } - } - - /* init FILE pointers */ - FL_end = 0; - FileList[0] = stdout; - for ( ; i < argc; i++) { - /* add a file to FileList */ - file = fopen(argv[i], opt_fopen); - if (!file) { continue; } - if (FL_end < FL_MAX) { - FileList[++FL_end] = file; + + /* init FILE pointers */ + FL_end = 0; + FileList[0] = stdout; + for (; i < argc; i++) { + /* add a file to FileList */ + file = fopen(argv[i], opt_fopen); + if (!file) { + continue; + } + if (FL_end < FL_MAX) { + FileList[++FL_end] = file; + } } - } - /* read and redirect */ - while ((c = (char) getchar()) && (!feof(stdin))) { - FL_apply(tee_fwrite, c); - } + /* read and redirect */ + while ((c = (char) getchar()) && (!feof(stdin))) { + FL_apply(tee_fwrite, c); + } - /* clean up */ - FL_apply(tee_fclose, 0); - exit(0); + /* clean up */ + FL_apply(tee_fclose, 0); + exit(0); } -/* $Id: tee.c,v 1.5 2000/02/07 05:29:42 erik Exp $ */ +/* $Id: tee.c,v 1.6 2000/02/08 19:58:47 erik Exp $ */ diff --git a/coreutils/touch.c b/coreutils/touch.c index d2d3e9484..a0f21acdd 100644 --- a/coreutils/touch.c +++ b/coreutils/touch.c @@ -1,3 +1,4 @@ +/* vi: set sw=4 ts=4: */ /* * Mini touch implementation for busybox * @@ -31,56 +32,50 @@ static const char touch_usage[] = "touch [-c] file [file ...]\n\n" -"Update the last-modified date on the given file[s].\n"; + "Update the last-modified date on the given file[s].\n"; -extern int -touch_main(int argc, char **argv) -{ - int fd; - int create=TRUE; - if (argc < 2) { - usage( touch_usage); - } - argc--; - argv++; +extern int touch_main(int argc, char **argv) +{ + int fd; + int create = TRUE; - /* Parse options */ - while (**argv == '-') { - while (*++(*argv)) switch (**argv) { - case 'c': - create = FALSE; - break; - default: - usage( touch_usage); - exit( FALSE); + if (argc < 2) { + usage(touch_usage); } argc--; argv++; - } - fd = open (*argv, (create==FALSE)? O_RDWR : O_RDWR | O_CREAT, 0644); - if (fd < 0 ) { - if (create==FALSE && errno == ENOENT) - exit( TRUE); - else { - perror("touch"); - exit( FALSE); + /* Parse options */ + while (**argv == '-') { + while (*++(*argv)) + switch (**argv) { + case 'c': + create = FALSE; + break; + default: + usage(touch_usage); + exit(FALSE); + } + argc--; + argv++; } - } - close( fd); - if (utime (*argv, NULL)) { - perror("touch"); - exit( FALSE); - } - else - exit( TRUE); -} - - - - - + fd = open(*argv, (create == FALSE) ? O_RDWR : O_RDWR | O_CREAT, 0644); + if (fd < 0) { + if (create == FALSE && errno == ENOENT) + exit(TRUE); + else { + perror("touch"); + exit(FALSE); + } + } + close(fd); + if (utime(*argv, NULL)) { + perror("touch"); + exit(FALSE); + } else + exit(TRUE); +} diff --git a/coreutils/tty.c b/coreutils/tty.c index 83abaffb5..8ac1c1fcd 100644 --- a/coreutils/tty.c +++ b/coreutils/tty.c @@ -1,3 +1,4 @@ +/* vi: set sw=4 ts=4: */ /* * Mini tty implementation for busybox * @@ -24,19 +25,23 @@ #include <sys/types.h> static const char tty_usage[] = "tty\n\n" -"Print the file name of the terminal connected to standard input.\n" -"\t-s\tprint nothing, only return an exit status\n"; + "Print the file name of the terminal connected to standard input.\n" -extern int tty_main(int argc, char **argv) { + "\t-s\tprint nothing, only return an exit status\n"; + +extern int tty_main(int argc, char **argv) +{ char *tty; if (argc > 1) { - if (argv[1][0] != '-' || argv[1][1] != 's') usage (tty_usage); - } - else { - tty = ttyname (0); - if (tty) puts (tty); - else puts ("not a tty"); + if (argv[1][0] != '-' || argv[1][1] != 's') + usage(tty_usage); + } else { + tty = ttyname(0); + if (tty) + puts(tty); + else + puts("not a tty"); } - exit (isatty (0) ? TRUE : FALSE); + exit(isatty(0) ? TRUE : FALSE); } diff --git a/coreutils/uname.c b/coreutils/uname.c index 9083edb04..9a1cb808a 100644 --- a/coreutils/uname.c +++ b/coreutils/uname.c @@ -1,3 +1,4 @@ +/* vi: set sw=4 ts=4: */ /* uname -- print system information Copyright (C) 1989-1999 Free Software Foundation, Inc. @@ -41,16 +42,17 @@ static const char uname_usage[] = - "uname [OPTION]...\n\n" - "Print certain system information. With no OPTION, same as -s.\n\n" - "Options:\n" - "\t-a\tprint all information\n" - "\t-m\tthe machine (hardware) type\n" - "\t-n\tprint the machine's network node hostname\n" - "\t-r\tprint the operating system release\n" - "\t-s\tprint the operating system name\n" - "\t-p\tprint the host processor type\n" - "\t-v\tprint the operating system version\n"; + "uname [OPTION]...\n\n" + "Print certain system information. With no OPTION, same as -s.\n\n" + "Options:\n" + "\t-a\tprint all information\n" + "\t-m\tthe machine (hardware) type\n" + "\t-n\tprint the machine's network node hostname\n" + "\t-r\tprint the operating system release\n" + "\t-s\tprint the operating system name\n" + + "\t-p\tprint the host processor type\n" + "\t-v\tprint the operating system version\n"; static void print_element(unsigned int mask, char *element); @@ -80,77 +82,78 @@ static unsigned char toprint; int uname_main(int argc, char **argv) { - struct utsname name; - char processor[256]; + struct utsname name; + char processor[256]; + #if defined(__sparc__) && defined(__linux__) - char *fake_sparc = getenv("FAKE_SPARC"); + char *fake_sparc = getenv("FAKE_SPARC"); #endif - toprint = 0; - - /* Parse any options */ - //fprintf(stderr, "argc=%d, argv=%s\n", argc, *argv); - while (--argc > 0 && **(++argv) == '-') { - while (*(++(*argv))) { - switch (**argv) { - case 's': - toprint |= PRINT_SYSNAME; - break; - case 'n': - toprint |= PRINT_NODENAME; - break; - case 'r': - toprint |= PRINT_RELEASE; - break; - case 'v': - toprint |= PRINT_VERSION; - break; - case 'm': - toprint |= PRINT_MACHINE; - break; - case 'p': - toprint |= PRINT_PROCESSOR; - break; - case 'a': - toprint = (PRINT_SYSNAME | PRINT_NODENAME | PRINT_RELEASE | - PRINT_PROCESSOR | PRINT_VERSION | - PRINT_MACHINE); - break; - default: - usage(uname_usage); - } + toprint = 0; + + /* Parse any options */ + //fprintf(stderr, "argc=%d, argv=%s\n", argc, *argv); + while (--argc > 0 && **(++argv) == '-') { + while (*(++(*argv))) { + switch (**argv) { + case 's': + toprint |= PRINT_SYSNAME; + break; + case 'n': + toprint |= PRINT_NODENAME; + break; + case 'r': + toprint |= PRINT_RELEASE; + break; + case 'v': + toprint |= PRINT_VERSION; + break; + case 'm': + toprint |= PRINT_MACHINE; + break; + case 'p': + toprint |= PRINT_PROCESSOR; + break; + case 'a': + toprint = (PRINT_SYSNAME | PRINT_NODENAME | PRINT_RELEASE | + PRINT_PROCESSOR | PRINT_VERSION | + PRINT_MACHINE); + break; + default: + usage(uname_usage); + } + } } - } - if (toprint == 0) - toprint = PRINT_SYSNAME; + if (toprint == 0) + toprint = PRINT_SYSNAME; - if (uname(&name) == -1) - perror("cannot get system name"); + if (uname(&name) == -1) + perror("cannot get system name"); #if defined (HAVE_SYSINFO) && defined (SI_ARCHITECTURE) - if (sysinfo(SI_ARCHITECTURE, processor, sizeof(processor)) == -1) - perror("cannot get processor type"); + if (sysinfo(SI_ARCHITECTURE, processor, sizeof(processor)) == -1) + perror("cannot get processor type"); } #else - strcpy(processor, "unknown"); + strcpy(processor, "unknown"); #endif #if defined(__sparc__) && defined(__linux__) - if (fake_sparc != NULL - && (fake_sparc[0] == 'y' - || fake_sparc[0] == 'Y')) strcpy(name.machine, "sparc"); + if (fake_sparc != NULL + && (fake_sparc[0] == 'y' + || fake_sparc[0] == 'Y')) strcpy(name.machine, "sparc"); #endif - print_element(PRINT_SYSNAME, name.sysname); - print_element(PRINT_NODENAME, name.nodename); - print_element(PRINT_RELEASE, name.release); - print_element(PRINT_VERSION, name.version); - print_element(PRINT_MACHINE, name.machine); - print_element(PRINT_PROCESSOR, processor); + print_element(PRINT_SYSNAME, name.sysname); + print_element(PRINT_NODENAME, name.nodename); + print_element(PRINT_RELEASE, name.release); + print_element(PRINT_VERSION, name.version); + print_element(PRINT_MACHINE, name.machine); + print_element(PRINT_PROCESSOR, processor); - exit(TRUE); + exit(TRUE); } /* If the name element set in MASK is selected for printing in `toprint', @@ -159,8 +162,8 @@ int uname_main(int argc, char **argv) static void print_element(unsigned int mask, char *element) { - if (toprint & mask) { - toprint &= ~mask; - printf("%s%c", element, toprint ? ' ' : '\n'); - } + if (toprint & mask) { + toprint &= ~mask; + printf("%s%c", element, toprint ? ' ' : '\n'); + } } diff --git a/coreutils/uniq.c b/coreutils/uniq.c index 965d290c2..1e41eaacd 100644 --- a/coreutils/uniq.c +++ b/coreutils/uniq.c @@ -1,3 +1,4 @@ +/* vi: set sw=4 ts=4: */ /* * Mini uniq implementation for busybox * @@ -27,119 +28,116 @@ #include <errno.h> static const char uniq_usage[] = -"uniq [OPTION]... [INPUT [OUTPUT]]\n" -"Discard all but one of successive identical lines from INPUT (or\n" -"standard input), writing to OUTPUT (or standard output).\n" -"\n" -"\t-h\tdisplay this help and exit\n" -"\n" -"A field is a run of whitespace, then non-whitespace characters.\n" -"Fields are skipped before chars.\n" -; + "uniq [OPTION]... [INPUT [OUTPUT]]\n" + "Discard all but one of successive identical lines from INPUT (or\n" + "standard input), writing to OUTPUT (or standard output).\n" + "\n" + "\t-h\tdisplay this help and exit\n" + + "\n" + "A field is a run of whitespace, then non-whitespace characters.\n" + "Fields are skipped before chars.\n"; /* max chars in line */ #define UNIQ_MAX 4096 -typedef void (Print)(FILE *, const char *); +typedef void (Print) (FILE *, const char *); -typedef int (Decide)(const char *, const char *); +typedef int (Decide) (const char *, const char *); /* container for two lines to be compared */ typedef struct { - char *a; - char *b; - int recurrence; - FILE *in; - FILE *out; - void *func; + char *a; + char *b; + int recurrence; + FILE *in; + FILE *out; + void *func; } Subject; /* set up all the variables of a uniq operation */ -static Subject * -subject_init(Subject *self, FILE *in, FILE *out, void *func) +static Subject *subject_init(Subject * self, FILE * in, FILE * out, + void *func) { - self->a = NULL; - self->b = NULL; - self->in = in; - self->out = out; - self->func = func; - self->recurrence = 0; - return self; + self->a = NULL; + self->b = NULL; + self->in = in; + self->out = out; + self->func = func; + self->recurrence = 0; + return self; } /* point a and b to the appropriate lines; * count the recurrences (if any) of a string; */ -static Subject * -subject_next(Subject *self) +static Subject *subject_next(Subject * self) { - /* tmp line holders */ - static char line[2][UNIQ_MAX]; - static int alternator = 0; - - if (fgets(line[alternator], UNIQ_MAX, self->in)) { - self->a = self->b; - self->b = line[alternator]; - alternator ^= 1; - return self; - } + /* tmp line holders */ + static char line[2][UNIQ_MAX]; + static int alternator = 0; + + if (fgets(line[alternator], UNIQ_MAX, self->in)) { + self->a = self->b; + self->b = line[alternator]; + alternator ^= 1; + return self; + } - return NULL; + return NULL; } -static Subject * -subject_last(Subject *self) +static Subject *subject_last(Subject * self) { - self->a = self->b; - self->b = NULL; - return self; + self->a = self->b; + self->b = NULL; + return self; } -static Subject * -subject_study(Subject *self) +static Subject *subject_study(Subject * self) { - if (self->a == NULL) { - return self; - } - if (self->b == NULL) { - fprintf(self->out, "%s", self->a); + if (self->a == NULL) { + return self; + } + if (self->b == NULL) { + fprintf(self->out, "%s", self->a); + return self; + } + if (strcmp(self->a, self->b) == 0) { + self->recurrence++; + } else { + fprintf(self->out, "%s", self->a); + self->recurrence = 0; + } return self; - } - if (strcmp(self->a, self->b) == 0) { - self->recurrence++; - } else { - fprintf(self->out, "%s", self->a); - self->recurrence = 0; - } - return self; } static int -set_file_pointers(int schema, FILE **in, FILE **out, char **argv) +set_file_pointers(int schema, FILE ** in, FILE ** out, char **argv) { - switch (schema) { + switch (schema) { case 0: - *in = stdin; - *out = stdout; - break; + *in = stdin; + *out = stdout; + break; case 1: - *in = fopen(argv[0], "r"); - *out = stdout; - break; + *in = fopen(argv[0], "r"); + *out = stdout; + break; case 2: - *in = fopen(argv[0], "r"); - *out = fopen(argv[1], "w"); - break; - } - if (*in == NULL) { - fprintf(stderr, "uniq: %s: %s\n", argv[0], strerror(errno)); - return errno; - } - if (*out == NULL) { - fprintf(stderr, "uniq: %s: %s\n", argv[1], strerror(errno)); - return errno; - } - return 0; + *in = fopen(argv[0], "r"); + *out = fopen(argv[1], "w"); + break; + } + if (*in == NULL) { + fprintf(stderr, "uniq: %s: %s\n", argv[0], strerror(errno)); + return errno; + } + if (*out == NULL) { + fprintf(stderr, "uniq: %s: %s\n", argv[1], strerror(errno)); + return errno; + } + return 0; } @@ -152,45 +150,44 @@ set_file_pointers(int schema, FILE **in, FILE **out, char **argv) /* it seems like GNU/uniq only takes one or two files as an option */ /* ________________________________________________________________________ */ -int -uniq_main(int argc, char **argv) +int uniq_main(int argc, char **argv) { - int i; - char opt; - FILE *in, *out; - Subject s; - - /* parse argv[] */ - for (i = 1; i < argc; i++) { - if (argv[i][0] == '-') { - opt = argv[i][1]; - switch (opt) { - case '-': - case 'h': - usage(uniq_usage); - default: - usage(uniq_usage); - } - } else { - break; + int i; + char opt; + FILE *in, *out; + Subject s; + + /* parse argv[] */ + for (i = 1; i < argc; i++) { + if (argv[i][0] == '-') { + opt = argv[i][1]; + switch (opt) { + case '-': + case 'h': + usage(uniq_usage); + default: + usage(uniq_usage); + } + } else { + break; + } } - } - /* 0 src: stdin; dst: stdout */ - /* 1 src: file; dst: stdout */ - /* 2 src: file; dst: file */ - if (set_file_pointers((argc - 1), &in, &out, &argv[i])) { - exit(1); - } + /* 0 src: stdin; dst: stdout */ + /* 1 src: file; dst: stdout */ + /* 2 src: file; dst: file */ + if (set_file_pointers((argc - 1), &in, &out, &argv[i])) { + exit(1); + } - subject_init(&s, in, out, NULL); - while (subject_next(&s)) { + subject_init(&s, in, out, NULL); + while (subject_next(&s)) { + subject_study(&s); + } + subject_last(&s); subject_study(&s); - } - subject_last(&s); - subject_study(&s); - exit(0); + exit(0); } -/* $Id: uniq.c,v 1.6 2000/02/07 05:29:42 erik Exp $ */ +/* $Id: uniq.c,v 1.7 2000/02/08 19:58:47 erik Exp $ */ diff --git a/coreutils/wc.c b/coreutils/wc.c index e69f0d899..8004e6294 100644 --- a/coreutils/wc.c +++ b/coreutils/wc.c @@ -1,3 +1,4 @@ +/* vi: set sw=4 ts=4: */ /* * Mini wc implementation for busybox * @@ -23,78 +24,82 @@ #include <stdio.h> static const char wc_usage[] = "wc [OPTION]... [FILE]...\n\n" -"Print line, word, and byte counts for each FILE, and a total line if\n" -"more than one FILE is specified. With no FILE, read standard input.\n" -"\t-c\tprint the byte counts\n" -"\t-l\tprint the newline counts\n" -"\t-L\tprint the length of the longest line\n" -"\t-w\tprint the word counts\n"; + "Print line, word, and byte counts for each FILE, and a total line if\n" + "more than one FILE is specified. With no FILE, read standard input.\n" + "\t-c\tprint the byte counts\n" + "\t-l\tprint the newline counts\n" + + "\t-L\tprint the length of the longest line\n" + "\t-w\tprint the word counts\n"; static int total_lines, total_words, total_chars, max_length; static int print_lines, print_words, print_chars, print_length; -void print_counts (int lines, int words, int chars, int length, - const char *name) { +void print_counts(int lines, int words, int chars, int length, + const char *name) +{ char const *space = ""; + if (print_lines) { - printf ("%7d", lines); + printf("%7d", lines); space = " "; } if (print_words) { - printf ("%s%7d", space, words); + printf("%s%7d", space, words); space = " "; } if (print_chars) { - printf ("%s%7d", space, chars); + printf("%s%7d", space, chars); space = " "; } if (print_length) - printf ("%s%7d", space, length); + printf("%s%7d", space, length); if (*name) - printf (" %s", name); - putchar ('\n'); + printf(" %s", name); + putchar('\n'); } -static void wc_file(FILE *file, const char *name) +static void wc_file(FILE * file, const char *name) { int lines, words, chars, length; int in_word = 0, linepos = 0; int c; + lines = words = chars = length = 0; while ((c = getc(file)) != EOF) { chars++; switch (c) { - case '\n': - lines++; - case '\r': - case '\f': - if (linepos > length) - length = linepos; - linepos = 0; - goto word_separator; - case '\t': - linepos += 8 - (linepos % 8); - goto word_separator; - case ' ': - linepos++; - case '\v': - word_separator: - if (in_word) { - in_word = 0; - words++; - } - break; - default: - linepos++; - in_word = 1; - break; + case '\n': + lines++; + case '\r': + case '\f': + if (linepos > length) + length = linepos; + linepos = 0; + goto word_separator; + case '\t': + linepos += 8 - (linepos % 8); + goto word_separator; + case ' ': + linepos++; + case '\v': + word_separator: + if (in_word) { + in_word = 0; + words++; + } + break; + default: + linepos++; + in_word = 1; + break; } } if (linepos > length) length = linepos; if (in_word) words++; - print_counts (lines, words, chars, length, name); + print_counts(lines, words, chars, length, name); total_lines += lines; total_words += words; total_chars += chars; @@ -104,28 +109,30 @@ static void wc_file(FILE *file, const char *name) fflush(stdout); } -int wc_main(int argc, char **argv) { +int wc_main(int argc, char **argv) +{ FILE *file; + total_lines = total_words = total_chars = max_length = 0; print_lines = print_words = print_chars = print_length = 0; while (--argc && **(++argv) == '-') { while (*++(*argv)) switch (**argv) { - case 'c': - print_chars = 1; - break; - case 'l': - print_lines = 1; - break; - case 'L': - print_length = 1; - break; - case 'w': - print_words = 1; - break; - default: - usage (wc_usage); + case 'c': + print_chars = 1; + break; + case 'l': + print_lines = 1; + break; + case 'L': + print_length = 1; + break; + case 'w': + print_words = 1; + break; + default: + usage(wc_usage); } } @@ -135,16 +142,14 @@ int wc_main(int argc, char **argv) { if (argc == 0) { wc_file(stdin, ""); exit(TRUE); - } - else if (argc == 1) { + } else if (argc == 1) { file = fopen(*argv, "r"); if (file == NULL) { perror(*argv); exit(FALSE); } wc_file(file, *argv); - } - else { + } else { while (argc-- > 0 && *argv != '\0' && strlen(*argv)) { file = fopen(*argv, "r"); if (file == NULL) { @@ -154,8 +159,8 @@ int wc_main(int argc, char **argv) { wc_file(file, *argv); argv++; } - print_counts (total_lines, total_words, total_chars, - max_length, "total"); + print_counts(total_lines, total_words, total_chars, + max_length, "total"); } exit(TRUE); } diff --git a/coreutils/whoami.c b/coreutils/whoami.c index 7fd5d01b2..3677c2fbc 100644 --- a/coreutils/whoami.c +++ b/coreutils/whoami.c @@ -1,3 +1,4 @@ +/* vi: set sw=4 ts=4: */ /* * Mini whoami implementation for busybox * @@ -24,21 +25,25 @@ #include <pwd.h> static const char whoami_usage[] = "whoami\n\n" -"Print the user name associated with the current effective user id.\n" -"Same as id -un.\n"; + "Print the user name associated with the current effective user id.\n" -extern int whoami_main(int argc, char **argv) { + "Same as id -un.\n"; + +extern int whoami_main(int argc, char **argv) +{ struct passwd *pw; uid_t uid; - if (argc > 1) usage (whoami_usage); + if (argc > 1) + usage(whoami_usage); - uid = geteuid (); - pw = getpwuid (uid); + uid = geteuid(); + pw = getpwuid(uid); if (pw) { - puts (pw->pw_name); - exit (TRUE); - } - fprintf (stderr, "%s: cannot find username for UID %u\n", argv[0], (unsigned) uid); - exit (FALSE); + puts(pw->pw_name); + exit(TRUE); + } + fprintf(stderr, "%s: cannot find username for UID %u\n", argv[0], + (unsigned) uid); + exit(FALSE); } diff --git a/coreutils/yes.c b/coreutils/yes.c index 96d6257d0..ac67845ac 100644 --- a/coreutils/yes.c +++ b/coreutils/yes.c @@ -1,3 +1,4 @@ +/* vi: set sw=4 ts=4: */ /* * Mini yes implementation for busybox * @@ -22,19 +23,22 @@ #include "internal.h" #include <stdio.h> -extern int yes_main(int argc, char **argv) { +extern int yes_main(int argc, char **argv) +{ int i; + if (argc == 1) while (1) - if (puts ("y") == EOF) { - perror ("yes"); + if (puts("y") == EOF) { + perror("yes"); exit(FALSE); } while (1) for (i = 1; i < argc; i++) - if (fputs (argv[i], stdout) == EOF || putchar (i == argc - 1 ? '\n' : ' ') == EOF) { - perror ("yes"); + if (fputs(argv[i], stdout) == EOF + || putchar(i == argc - 1 ? '\n' : ' ') == EOF) { + perror("yes"); exit(FALSE); } exit(TRUE); |