bug-coreutils
[Top][All Lists]
Advanced

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: bsearch utility


From: Sorav Bansal
Subject: Re: bsearch utility
Date: Thu, 21 Jul 2005 07:08:46 -0700
User-agent: Mozilla Thunderbird 0.8 (X11/20050528)

As promised, I am sending you an implementation of 'bsearch' that has identical options to 'sort'. The utility has been written to optimize the number of disk reads. The main functions in this code are 'binary_search()' and 'linear_search()'.

I have unit-tested the search-logic extensively. I have also tested the option-parsing logic, though not very extensively. Since most of the code to read the options was taken from 'sort', I do not imagine any problems there.

I am attaching the source file bsearch.c and the man page bsearch.1

I look forward to your review/comments.

Regards,
Sorav
.\" DO NOT MODIFY THIS FILE!  It was generated by help2man 1.35.
.TH BSEARCH "1" "July 2005" "bsearch (coreutils) 5.0" "User Commands"
.SH NAME
bsearch \- manual page for bsearch (coreutils) 5.0
.SH SYNOPSIS
.B bsearch
[\fIOPTION\fR]... \fISTRING \fR[\fIFILE\fR]...
.SH DESCRIPTION
Display lines matching STRING and given key fields using binary search in a
file sorted using sort(1) with the same options and key fields
Ordering options:
.PP
Mandatory arguments to long options are mandatory for short options too.
.HP
\fB\-b\fR, \fB\-\-ignore\-leading\-blanks\fR ignore leading blanks
.TP
\fB\-d\fR, \fB\-\-dictionary\-order\fR
consider only blanks and alphanumeric characters
.TP
\fB\-f\fR, \fB\-\-ignore\-case\fR
fold lower case to upper case characters
.TP
\fB\-g\fR, \fB\-\-general\-numeric\-comp\fR
compare according to general numerical value
.TP
\fB\-i\fR, \fB\-\-ignore\-nonprinting\fR
consider only printable characters
.TP
\fB\-M\fR, \fB\-\-month\-compare\fR
compare (unknown) < `JAN' < ... < `DEC'
.TP
\fB\-n\fR, \fB\-\-numeric\-compare\fR
compare according to string numerical value
.TP
\fB\-r\fR, \fB\-\-reverse\fR
the file was sorted using reverse order
.PP
Other options:
.TP
\fB\-k\fR, \fB\-\-key\fR=\fIPOS1[\fR,POS2]
start a key at POS1, end it at POS 2 (origin 1)
.TP
\fB\-o\fR, \fB\-\-output\fR=\fIFILE\fR
write result to FILE instead of standard output
.TP
\fB\-L\fR, \fB\-\-line\-size\fR=\fISIZE\fR
use SIZE as the average line buffer size
.HP
\fB\-t\fR, \fB\-\-field\-separator\fR=\fISEP\fR use SEP instead of non\- to 
whitespace transition
.TP
\fB\-z\fR, \fB\-\-zero\-terminated\fR
lines end with 0 byte, not newline
.TP
\fB\-\-help\fR
display this help and exit
.TP
\fB\-\-version\fR
output version information and exit
.PP
POS is F[.C][OPTS], where F is the field number and C the character position
in the field.  OPTS is one or more single\-letter ordering options, which
override global ordering options for that key.  If no key is given, use the
entire line as the key.
.PP
SIZE may be followed by the following multiplicative suffixes:
b 1, K 1024 (default), and so on for M, G, T, P, E, Z, Y.
.PP
With no FILE, or when FILE is \-, read standard input.
.PP
*** WARNING ***
The locale specified by the environment affects search and sort order.
Set LC_ALL=C to get the traditional sort order that uses
native byte values.
.SH AUTHOR
Written by 'Under Review'.
.SH "REPORTING BUGS"
Report bugs to <address@hidden>.
.SH COPYRIGHT
Copyright \(co 2003 Free Software Foundation, Inc.
.br
This is free software; see the source for copying conditions.  There is NO
warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
.SH "SEE ALSO"
The full documentation for
.B bsearch
is maintained as a Texinfo manual.  If the
.B info
and
.B bsearch
programs are properly installed at your site, the command
.IP
.B info bsearch
.PP
should give you access to the complete manual.
/* bsearch : Submitted for code review by Sorav Bansal (address@hidden)
   to address@hidden
*/

#include <config.h>

#include <getopt.h>
#include <sys/types.h>
#include <signal.h>
#include <stdio.h>
#include <assert.h>
#include "system.h"
#include "long-options.h"
#include "error.h"
#include "hard-locale.h"
#include "inttostr.h"
#include "physmem.h"
#include "posixver.h"
#include "stdio-safer.h"
#include "xmemcoll.h"
#include "xstrtol.h"

#if HAVE_SYS_RESOURCE_H
# include <sys/resource.h>
#endif
#ifndef RLIMIT_DATA
struct rlimit { size_t rlim_cur; };
# define getrlimit(Resource, Rlp) (-1)
#endif

/* The official name of this program (e.g., no `g' prefix).  */
#define PROGRAM_NAME "bsearch"

#define AUTHORS N_ ("\'Under Review\'")

#if HAVE_LANGINFO_CODESET
# include <langinfo.h>
#endif

#ifndef SA_NOCLDSTOP
# define sigprocmask(How, Set, Oset) /* empty */
# define sigset_t int
#endif

#ifndef STDC_HEADERS
double strtod ();
#endif

/* Undefine, to avoid warning about redefinition on some systems.  */
/* FIXME: Remove these: use MIN/MAX from sys2.h.  */
#undef min
#define min(a, b) ((a) < (b) ? (a) : (b))
#undef max
#define max(a, b) ((a) > (b) ? (a) : (b))

#define UCHAR_LIM (UCHAR_MAX + 1)
#define UCHAR(c) ((unsigned char) (c))

/* Use this as exit status in case of error, not EXIT_FAILURE.  This
   is necessary because EXIT_FAILURE is usually 1 and POSIX requires
   that sort exit with status 1 IFF invoked with -c and the input is
   not properly sorted.  Any other irregular exit must exit with a
   status code greater than 1.  */
#define SEARCH_FAILURE 2

#define C_DECIMAL_POINT '.'
#define NEGATION_SIGN   '-'
#define NUMERIC_ZERO    '0'

#if HAVE_SETLOCALE

static char decimal_point;
static int th_sep; /* if CHAR_MAX + 1, then there is no thousands separator */

/* Nonzero if the corresponding locales are hard.  */
static int hard_LC_COLLATE;
# if HAVE_NL_LANGINFO
static int hard_LC_TIME;
# endif

# define IS_THOUSANDS_SEP(x) ((x) == th_sep)

#else

# define decimal_point C_DECIMAL_POINT
# define IS_THOUSANDS_SEP(x) 0

#endif

#define NONZERO(x) (x != 0)

/* The kind of blanks for '-b' to skip in various options. */
enum blanktype { bl_start, bl_end, bl_both };

/* The character marking end of line. Default to \n. */
static int eolchar = '\n';

/* Lines are held in core as counted strings. */
struct line
{
  char *text;                   /* Text of the line. */
  size_t length;                /* Length including final newline. */
  char *keybeg;                 /* Start of first key. */
  char *keylim;                 /* Limit of first key. */
};

struct line_buffer
{
  char *buf ;
  size_t alloc;
  struct line line ;
};

struct keyfield
{
  size_t sword;                 /* Zero-origin 'word' to start at. */
  size_t schar;                 /* Additional characters to skip. */
  int skipsblanks;              /* Skip leading white space at start. */
  size_t eword;                 /* Zero-origin first word after field. */
  size_t echar;                 /* Additional characters in field. */
  int skipeblanks;              /* Skip trailing white space at finish. */
  int *ignore;                  /* Boolean array of characters to ignore. */
  char *translate;              /* Translation applied to characters. */
  int numeric;                  /* Flag for numeric comparison.  Handle
                                   strings of digits with optional decimal
                                   point, but no exponential notation. */
  int general_numeric;          /* Flag for general, numeric comparison.
                                   Handle numbers in exponential notation. */
  int month;                    /* Flag for comparison by month name. */
  int reverse;                  /* Reverse the sense of comparison. */
  struct keyfield *next;        /* Next keyfield to try. */
};

struct month
{
  char *name;
  int val;
};

/* The name this program was run with. */
char *program_name;

/* FIXME: None of these tables work with multibyte character sets.
   Also, there are many other bugs when handling multibyte characters,
   or even unibyte encodings where line boundaries are not in the
   initial shift state.  One way to fix this is to rewrite `sort' to
   use wide characters internally, but doing this with good
   performance is a bit tricky.  */

/* Table of white space. */
static int blanks[UCHAR_LIM];

/* Table of non-printing characters. */
static int nonprinting[UCHAR_LIM];

/* Table of non-dictionary characters (not letters, digits, or blanks). */
static int nondictionary[UCHAR_LIM];

/* Translation table folding lower case to upper.  */
static char fold_toupper[UCHAR_LIM];

#define MONTHS_PER_YEAR 12

/* Table mapping month names to integers.
   Alphabetic order allows binary search. */
static struct month monthtab[] =
{
  {"APR", 4},
  {"AUG", 8},
  {"DEC", 12},
  {"FEB", 2},
  {"JAN", 1},
  {"JUL", 7},
  {"JUN", 6},
  {"MAR", 3},
  {"MAY", 5},
  {"NOV", 11},
  {"OCT", 10},
  {"SEP", 9}
};

/* Minimum sort size; the code might not work with smaller sizes.  */
#define DISK_SECTOR_SIZE (512)

/* The approximate length of a line (setting this speeds up the iterative
   procedure to infer line length) */
static size_t default_line_size = DISK_SECTOR_SIZE ;

/* The guessed size for non-regular files.  */
#define INPUT_FILE_SIZE_GUESS (1024 * 1024)

/* Flag to reverse the order of all comparisons. */
static int reverse;

/* Tab character separating fields.  If NUL, then fields are separated
   by the empty string between a non-whitespace character and a whitespace
   character. */
static char tab;

/* Nonzero if any of the input files are the standard input. */
static int have_read_stdin;

/* List of key field comparisons to be tried.  */
static struct keyfield *keylist;

/* Pointer to the string holding the output file */
char const *output_file = NULL ;

void
usage (int status)
{
  if (status != 0)
    fprintf (stderr, _("Try `%s --help' for more information.\n"),
             program_name);
  else
    {
      printf (_("\
Usage: %s [OPTION]... STRING [FILE]...\n\
"),
              program_name);
      fputs (_("\
Display lines matching STRING and given key fields using binary search in a\n\
file sorted using sort(1) with the same options and key fields\n\
Ordering options:\n\
\n\
"), stdout);
      fputs (_("\
Mandatory arguments to long options are mandatory for short options too.\n\
"), stdout);
      fputs (_("\
  -b, --ignore-leading-blanks ignore leading blanks\n\
  -d, --dictionary-order      consider only blanks and alphanumeric 
characters\n\
  -f, --ignore-case           fold lower case to upper case characters\n\
"), stdout);
      fputs (_("\
  -g, --general-numeric-comp  compare according to general numerical value\n\
  -i, --ignore-nonprinting    consider only printable characters\n\
  -M, --month-compare         compare (unknown) < `JAN' < ... < `DEC'\n\
  -n, --numeric-compare       compare according to string numerical value\n\
  -r, --reverse               the file was sorted using reverse order\n\
\n\
"), stdout);
      fputs (_("\
Other options:\n\
\n\
  -k, --key=POS1[,POS2]     start a key at POS1, end it at POS 2 (origin 1)\n\
  -o, --output=FILE         write result to FILE instead of standard output\n\
  -L, --line-size=SIZE      use SIZE as the average line buffer size\n\
"), stdout);
      printf (_("\
  -t, --field-separator=SEP use SEP instead of non- to whitespace transition\n\
"));
      fputs (_("\
  -z, --zero-terminated     lines end with 0 byte, not newline\n\
"), stdout);
      fputs (HELP_OPTION_DESCRIPTION, stdout);
      fputs (VERSION_OPTION_DESCRIPTION, stdout);
      fputs (_("\
\n\
POS is F[.C][OPTS], where F is the field number and C the character position\n\
in the field.  OPTS is one or more single-letter ordering options, which\n\
override global ordering options for that key.  If no key is given, use the\n\
entire line as the key.\n\
\n\
SIZE may be followed by the following multiplicative suffixes:\n\
"), stdout);
      fputs (_("\
b 1, K 1024 (default), and so on for M, G, T, P, E, Z, Y.\n\
\n\
With no FILE, or when FILE is -, read standard input.\n\
\n\
*** WARNING ***\n\
The locale specified by the environment affects search and sort order.\n\
Set LC_ALL=C to get the traditional sort order that uses\n\
native byte values.\n\
"), stdout );
      printf (_("\nReport bugs to <%s>.\n"), PACKAGE_BUGREPORT);
    }
  /* Don't use EXIT_FAILURE here in case it is defined to be 1.
     POSIX requires that sort return 1 IFF invoked with -c and
     the input is not properly sorted.  */
  assert (status == 0 || status == SEARCH_FAILURE);
  exit (status);
}

#define COMMON_SHORT_OPTIONS "bdfgik:Mno:rL:t:z"

static struct option const long_options[] =
{
  {"ignore-leading-blanks", no_argument, NULL, 'b'},
  {"dictionary-order", no_argument, NULL, 'd'},
  {"ignore-case", no_argument, NULL, 'f'},
  {"general-numeric-comp", no_argument, NULL, 'g'},
  {"ignore-nonprinting", no_argument, NULL, 'i'},
  {"key", required_argument, NULL, 'k'},
  {"month-compare", no_argument, NULL, 'M'},
  {"numeric-compare", no_argument, NULL, 'n'},
  {"output", required_argument, NULL, 'o'},
  {"reverse", no_argument, NULL, 'r'},
  {"line-size", required_argument, NULL, 'L'},
  {"field-separator", required_argument, NULL, 't'},
  {"zero-terminated", no_argument, NULL, 'z'},
  {GETOPT_HELP_OPTION_DECL},
  {GETOPT_VERSION_OPTION_DECL},
  {0, 0, 0, 0},
};

/* The set of signals that are caught.  */
static sigset_t caught_signals;

/* Report MESSAGE for FILE, then clean up and exit.  */

static void die (char const *, char const *) ATTRIBUTE_NORETURN;
static void
die (char const *message, char const *file)
{
  error (0, errno, "%s: %s", message, file);
  exit (SEARCH_FAILURE);
}

static FILE *
xfopen (const char *file, const char *how)
{
  FILE *fp;

  if (STREQ (file, "-"))
    {
      if (*how == 'r')
        {
          have_read_stdin = 1;
          fp = stdin;
        }
      else
        fp = stdout;
    }
  else
    {
      if ((fp = fopen_safer (file, how)) == NULL)
        die (_("open failed"), file);
    }

  return fp;
}

/* Close FP, whose name is FILE, and report any errors.  */

static void
xfclose (FILE *fp, char const *file)
{
  if (fp == stdin)
    {
      /* Allow reading stdin from tty more than once. */
      if (feof (fp))
        clearerr (fp);
    }
  else
    {
      if (fclose (fp) != 0)
        die (_("close failed"), file);
    }
}

static void
write_bytes (const char *buf, size_t n_bytes, FILE *fp, const char *output_file)
{
  if (fwrite (buf, 1, n_bytes, fp) != n_bytes)
    die (_("write failed"), output_file);
}

#if HAVE_NL_LANGINFO

static int
struct_month_cmp (const void *m1, const void *m2)
{
  return strcmp (((const struct month *) m1)->name,
                 ((const struct month *) m2)->name);
}

#endif

/* Initialize the character class tables. */

static void
inittables (void)
{
  int i;

  for (i = 0; i < UCHAR_LIM; ++i)
    {
      if (ISBLANK (i))
        blanks[i] = 1;
      if (!ISPRINT (i))
        nonprinting[i] = 1;
      if (!ISALNUM (i) && !ISBLANK (i))
        nondictionary[i] = 1;
      if (ISLOWER (i))
        fold_toupper[i] = toupper (i);
      else
        fold_toupper[i] = i;
    }

#if HAVE_NL_LANGINFO
  /* If we're not in the "C" locale, read different names for months.  */
  if (hard_LC_TIME)
    {
      for (i = 0; i < MONTHS_PER_YEAR; i++)
        {
          char *s;
          size_t s_len;
          size_t j;
          char *name;

          s = (char *) nl_langinfo (ABMON_1 + i);
          s_len = strlen (s);
          monthtab[i].name = name = (char *) xmalloc (s_len + 1);
          monthtab[i].val = i + 1;

          for (j = 0; j < s_len; j++)
            name[j] = fold_toupper[UCHAR (s[j])];
          name[j] = '\0';
        }
      qsort ((void *) monthtab, MONTHS_PER_YEAR,
             sizeof (struct month), struct_month_cmp);
    }
#endif
}

/* Specify the average size of a line (this can speed up the iterative
   process of inferring the length of a line) */
static void
specify_line_size (char const *s)
{
  uintmax_t n;
  char *suffix;
  enum strtol_error e = xstrtoumax (s, &suffix, 10, &n, "EgGkKmMPtTYZ");

  /* The default unit is KiB.  */
  if (e == LONGINT_OK && ISDIGIT (suffix[-1]))
    {
      if (n <= UINTMAX_MAX / 1024)
        n *= 1024;
      else
        e = LONGINT_OVERFLOW;
    }

  /* A 'b' suffix means bytes; a '%' suffix means percent of memory.  */
  if (e == LONGINT_INVALID_SUFFIX_CHAR && ISDIGIT (suffix[-1]) && ! suffix[1])
    switch (suffix[0])
      {
      case 'b':
        e = LONGINT_OK;
        break;

      case '%':
        {
          double mem = physmem_total () * n / 100;

          /* Use "<", not "<=", to avoid problems with rounding.  */
          if (mem < UINTMAX_MAX)
            {
              n = mem;
              e = LONGINT_OK;
            }
          else
            e = LONGINT_OVERFLOW;
        }
        break;
      }

  if (e == LONGINT_OK)
    {
      default_line_size = n;
      if (default_line_size == n)
        {
          default_line_size = MAX (default_line_size, DISK_SECTOR_SIZE);
          return;
        }

      e = LONGINT_OVERFLOW;
    }

  STRTOL_FATAL_ERROR (s, _("line size"), e);
}

static void
init_line_buffer (struct line_buffer *buf, size_t alloc)
{
  for (;;)
    {
      buf->buf = malloc (alloc);
      if (buf->buf)
        break;
      alloc /= 2;
      if (alloc <= 1)
        xalloc_die ();
    }

  buf->alloc = alloc;
  buf->line.text = NULL ;
  buf->line.length = 0 ;
}

/* Return a pointer to the first character of the field specified
   by KEY in LINE. */

static char *
begfield (const struct line *line, const struct keyfield *key)
{
  register char *ptr = line->text, *lim = ptr + line->length - 1;
  register size_t sword = key->sword;
  register size_t schar = key->schar;
  register size_t remaining_bytes;

  if (tab)
    while (ptr < lim && sword--)
      {
        while (ptr < lim && *ptr != tab)
          ++ptr;
        if (ptr < lim)
          ++ptr;
      }
  else
    while (ptr < lim && sword--)
      {
        while (ptr < lim && blanks[UCHAR (*ptr)])
          ++ptr;
        while (ptr < lim && !blanks[UCHAR (*ptr)])
          ++ptr;
      }

  if (key->skipsblanks)
    while (ptr < lim && blanks[UCHAR (*ptr)])
      ++ptr;

  /* Advance PTR by SCHAR (if possible), but no further than LIM.  */
  remaining_bytes = lim - ptr;
  if (schar < remaining_bytes)
    ptr += schar;
  else
    ptr = lim;

  return ptr;
}

/* Return the limit of (a pointer to the first character after) the field
   in LINE specified by KEY. */

static char *
limfield (const struct line *line, const struct keyfield *key)
{
  register char *ptr = line->text, *lim = ptr + line->length - 1;
  register size_t eword = key->eword, echar = key->echar;
  register size_t remaining_bytes;

  /* Note: from the POSIX spec:
     The leading field separator itself is included in
     a field when -t is not used.  FIXME: move this comment up... */

  /* Move PTR past EWORD fields or to one past the last byte on LINE,
     whichever comes first.  If there are more than EWORD fields, leave
     PTR pointing at the beginning of the field having zero-based index,
     EWORD.  If a delimiter character was specified (via -t), then that
     `beginning' is the first character following the delimiting TAB.
     Otherwise, leave PTR pointing at the first `blank' character after
     the preceding field.  */
  if (tab)
    while (ptr < lim && eword--)
      {
        while (ptr < lim && *ptr != tab)
          ++ptr;
        if (ptr < lim && (eword | echar))
          ++ptr;
      }
  else
    while (ptr < lim && eword--)
      {
        while (ptr < lim && blanks[UCHAR (*ptr)])
          ++ptr;
        while (ptr < lim && !blanks[UCHAR (*ptr)])
          ++ptr;
      }

#ifdef POSIX_UNSPECIFIED
  /* The following block of code makes GNU sort incompatible with
     standard Unix sort, so it's ifdef'd out for now.
     The POSIX spec isn't clear on how to interpret this.
     FIXME: request clarification.

     From: address@hidden (Karl Heuer)
     Date: Thu, 30 May 96 12:20:41 -0400
     [Translated to POSIX 1003.1-2001 terminology by Paul Eggert.]

     [...]I believe I've found another bug in `sort'.

     $ cat /tmp/sort.in
     a b c 2 d
     pq rs 1 t
     $ textutils-1.15/src/sort -k1.7,1.7 </tmp/sort.in
     a b c 2 d
     pq rs 1 t
     $ /bin/sort -k1.7,1.7 </tmp/sort.in
     pq rs 1 t
     a b c 2 d

     Unix sort produced the answer I expected: sort on the single character
     in column 7.  GNU sort produced different results, because it disagrees
     on the interpretation of the key-end spec "M.N".  Unix sort reads this
     as "skip M-1 fields, then N-1 characters"; but GNU sort wants it to mean
     "skip M-1 fields, then either N-1 characters or the rest of the current
     field, whichever comes first".  This extra clause applies only to
     key-ends, not key-starts.
     */

  /* Make LIM point to the end of (one byte past) the current field.  */
  if (tab)
    {
      char *newlim;
      newlim = memchr (ptr, tab, lim - ptr);
      if (newlim)
        lim = newlim;
    }
  else
    {
      char *newlim;
      newlim = ptr;
      while (newlim < lim && blanks[UCHAR (*newlim)])
        ++newlim;
      while (newlim < lim && !blanks[UCHAR (*newlim)])
        ++newlim;
      lim = newlim;
    }
#endif

  /* If we're skipping leading blanks, don't start counting characters
     until after skipping past any leading blanks.  */
  if (key->skipsblanks)
    while (ptr < lim && blanks[UCHAR (*ptr)])
      ++ptr;

  /* Advance PTR by ECHAR (if possible), but no further than LIM.  */
  remaining_bytes = lim - ptr;
  if (echar < remaining_bytes)
    ptr += echar;
  else
    ptr = lim;

  return ptr;
}

/* FIXME */

static void
trim_trailing_blanks (const char *a_start, char **a_end)
{
  while (*a_end > a_start && blanks[UCHAR (*(*a_end - 1))])
    --(*a_end);
}

/* Fill LINE with the addresses START and END that denote the start and end
   of the line respectively. Also, precompute the position of the first key
*/
static void
make_line (struct line *line, char *start, char *end)
{
  struct keyfield const *key = keylist ;
  line->text = start ;
  line->length = (end - start) + 1 ;

  if (key) {
    /* Precompute the position of the first key for
       efficiency. */
    line->keylim = (key->eword == (size_t) -1
                    ? end
                    : limfield (line, key));

    if (key->sword != (size_t) -1)
      line->keybeg = begfield (line, key);
    else
      {
        if (key->skipsblanks)
          while (blanks[UCHAR (*start)])
            start++;
          line->keybeg = start;
      }
    if (key->skipeblanks)
      trim_trailing_blanks (line->keybeg, &line->keylim);
  }
}

/* Get the closest line starting at BEGIN in file FILE (pointed to by FP).
 * The closest line is obtained by searching for the next two EOL characters
 * and filling BUF with the line represented by the characters in between.
 * BUF is realloc()ed if needed to fit the line. The function returns the
 * file offset of the returned line, if successful. Returns -1 if no line
 * was found starting at BEGIN, or an error was encountered
 */
static off_t
get_closest_line (struct line_buffer *buf,
                  off_t begin,
                  register FILE *fp,
                  char const *file)
{
  char *start = NULL, *end = NULL ;
  size_t buf_used = 0 ;

  if (fseeko (fp, begin, SEEK_SET) < 0)
    die (_("seek error"), file);

  for (;;)
    {
      char *ptr = buf->buf + buf_used ;
      size_t readsize = (buf->alloc - 1) - buf_used ;
      size_t bytes_read = fread (ptr, 1, readsize, fp) ;
      char *ptrlim = ptr + bytes_read ;

      if (bytes_read != readsize)
        {
          if (ferror (fp))
            die (_("read failed"), file) ;
          if (feof (fp))
            {
              if (buf->buf == ptrlim)
                return -1 ;
              if (ptrlim[-1] != eolchar)
                *ptrlim++ = eolchar ;
            }
        }

      if (!start)
        {
          if ((start = memchr (ptr, eolchar, ptrlim - ptr)))
            start++ ;
        }
      if (start && !end)
        {
          char *scan_start = max (start, ptr) ;
          if ((end = memchr (scan_start, eolchar, ptrlim - ptr)))
            {
              make_line (&buf->line, start, end) ;
              return (ftello(fp) + (start-ptrlim)) ;
            }
        }

        buf_used = ptrlim - buf->buf ;

        /* The current input line is too long to fit in the buffer.
           Double the buffer size and try again.  */
        if (2 * buf->alloc < buf->alloc)
          xalloc_die ();
        buf->alloc *= 2;
        buf->buf = xrealloc (buf->buf, buf->alloc);
    }
}

/* Compare strings A and B containing decimal fractions < 1.  Each string
   should begin with a decimal point followed immediately by the digits
   of the fraction.  Strings not of this form are considered to be zero. */

/* The goal here, is to take two numbers a and b... compare these
   in parallel.  Instead of converting each, and then comparing the
   outcome.  Most likely stopping the comparison before the conversion
   is complete.  The algorithm used, in the old sort:

   Algorithm: fraccompare
   Action   : compare two decimal fractions
   accepts  : char *a, char *b
   returns  : -1 if a<b, 0 if a=b, 1 if a>b.
   implement:

   if *a == decimal_point AND *b == decimal_point
     find first character different in a and b.
     if both are digits, return the difference *a - *b.
     if *a is a digit
       skip past zeros
       if digit return 1, else 0
     if *b is a digit
       skip past zeros
       if digit return -1, else 0
   if *a is a decimal_point
     skip past decimal_point and zeros
     if digit return 1, else 0
   if *b is a decimal_point
     skip past decimal_point and zeros
     if digit return -1, else 0
   return 0 */

static int
fraccompare (register const char *a, register const char *b)
{
  if (*a == decimal_point && *b == decimal_point)
    {
      while (*++a == *++b)
        if (! ISDIGIT (*a))
          return 0;
      if (ISDIGIT (*a) && ISDIGIT (*b))
        return *a - *b;
      if (ISDIGIT (*a))
        goto a_trailing_nonzero;
      if (ISDIGIT (*b))
        goto b_trailing_nonzero;
      return 0;
    }
  else if (*a++ == decimal_point)
    {
    a_trailing_nonzero:
      while (*a == NUMERIC_ZERO)
        a++;
      return ISDIGIT (*a);
    }
  else if (*b++ == decimal_point)
    {
    b_trailing_nonzero:
      while (*b == NUMERIC_ZERO)
        b++;
      return - ISDIGIT (*b);
    }
  return 0;
}

/* Compare strings A and B as numbers without explicitly converting them to
   machine numbers.  Comparatively slow for short strings, but asymptotically
   hideously fast. */

static int
numcompare (register const char *a, register const char *b)
{
  register int tmpa, tmpb, tmp;
  register size_t loga, logb;

  tmpa = *a;
  tmpb = *b;

  while (blanks[UCHAR (tmpa)])
    tmpa = *++a;
  while (blanks[UCHAR (tmpb)])
    tmpb = *++b;

  if (tmpa == NEGATION_SIGN)
    {
      do
        tmpa = *++a;
      while (tmpa == NUMERIC_ZERO || IS_THOUSANDS_SEP (tmpa));
      if (tmpb != NEGATION_SIGN)
        {
          if (tmpa == decimal_point)
            do
              tmpa = *++a;
            while (tmpa == NUMERIC_ZERO);
          if (ISDIGIT (tmpa))
            return -1;
          while (tmpb == NUMERIC_ZERO || IS_THOUSANDS_SEP (tmpb))
            tmpb = *++b;
          if (tmpb == decimal_point)
            do
              tmpb = *++b;
            while (tmpb == NUMERIC_ZERO);
          if (ISDIGIT (tmpb))
            return -1;
          return 0;
        }
      do
        tmpb = *++b;
      while (tmpb == NUMERIC_ZERO || IS_THOUSANDS_SEP (tmpb));

      while (tmpa == tmpb && ISDIGIT (tmpa))
        {
          do
            tmpa = *++a;
          while (IS_THOUSANDS_SEP (tmpa));
          do
            tmpb = *++b;
          while (IS_THOUSANDS_SEP (tmpb));
        }

      if ((tmpa == decimal_point && !ISDIGIT (tmpb))
          || (tmpb == decimal_point && !ISDIGIT (tmpa)))
        return -fraccompare (a, b);

      tmp = tmpb - tmpa;

      for (loga = 0; ISDIGIT (tmpa); ++loga)
        do
          tmpa = *++a;
        while (IS_THOUSANDS_SEP (tmpa));

      for (logb = 0; ISDIGIT (tmpb); ++logb)
        do
          tmpb = *++b;
        while (IS_THOUSANDS_SEP (tmpb));

      if (loga != logb)
        return loga < logb ? 1 : -1;

      if (!loga)
        return 0;

      return tmp;
    }
  else if (tmpb == NEGATION_SIGN)
    {
      do
        tmpb = *++b;
      while (tmpb == NUMERIC_ZERO || IS_THOUSANDS_SEP (tmpb));
      if (tmpb == decimal_point)
        do
          tmpb = *++b;
        while (tmpb == NUMERIC_ZERO);
      if (ISDIGIT (tmpb))
        return 1;
      while (tmpa == NUMERIC_ZERO || IS_THOUSANDS_SEP (tmpa))
        tmpa = *++a;
      if (tmpa == decimal_point)
        do
          tmpa = *++a;
        while (tmpa == NUMERIC_ZERO);
      if (ISDIGIT (tmpa))
        return 1;
      return 0;
    }
  else
    {
      while (tmpa == NUMERIC_ZERO || IS_THOUSANDS_SEP (tmpa))
        tmpa = *++a;
      while (tmpb == NUMERIC_ZERO || IS_THOUSANDS_SEP (tmpb))
        tmpb = *++b;

      while (tmpa == tmpb && ISDIGIT (tmpa))
        {
          do
            tmpa = *++a;
          while (IS_THOUSANDS_SEP (tmpa));
          do
            tmpb = *++b;
          while (IS_THOUSANDS_SEP (tmpb));
        }

      if ((tmpa == decimal_point && !ISDIGIT (tmpb))
          || (tmpb == decimal_point && !ISDIGIT (tmpa)))
        return fraccompare (a, b);

      tmp = tmpa - tmpb;

      for (loga = 0; ISDIGIT (tmpa); ++loga)
        do
          tmpa = *++a;
        while (IS_THOUSANDS_SEP (tmpa));

      for (logb = 0; ISDIGIT (tmpb); ++logb)
        do
          tmpb = *++b;
        while (IS_THOUSANDS_SEP (tmpb));

      if (loga != logb)
        return loga < logb ? -1 : 1;

      if (!loga)
        return 0;

      return tmp;
    }
}

static int
general_numcompare (const char *sa, const char *sb)
{
  /* FIXME: add option to warn about failed conversions.  */
  /* FIXME: maybe add option to try expensive FP conversion
     only if A and B can't be compared more cheaply/accurately.  */

  char *ea;
  char *eb;
  double a = strtod (sa, &ea);
  double b = strtod (sb, &eb);

  /* Put conversion errors at the start of the collating sequence.  */
  if (sa == ea)
    return sb == eb ? 0 : -1;
  if (sb == eb)
    return 1;

  /* Sort numbers in the usual way, where -0 == +0.  Put NaNs after
     conversion errors but before numbers; sort them by internal
     bit-pattern, for lack of a more portable alternative.  */
  return (a < b ? -1
          : a > b ? 1
          : a == b ? 0
          : b == b ? -1
          : a == a ? 1
          : memcmp ((char *) &a, (char *) &b, sizeof a));
}

/* Return an integer in 1..12 of the month name S with length LEN.
   Return 0 if the name in S is not recognized.  */

static int
getmonth (const char *s, size_t len)
{
  char *month;
  register size_t i;
  register int lo = 0, hi = MONTHS_PER_YEAR, result;

  while (len > 0 && blanks[UCHAR (*s)])
    {
      ++s;
      --len;
    }

  if (len == 0)
    return 0;

  month = (char *) alloca (len + 1);
  for (i = 0; i < len; ++i)
    month[i] = fold_toupper[UCHAR (s[i])];
  while (blanks[UCHAR (month[i - 1])])
    --i;
  month[i] = '\0';

  do
    {
      int ix = (lo + hi) / 2;

      if (strncmp (month, monthtab[ix].name, strlen (monthtab[ix].name)) < 0)
        hi = ix;
      else
        lo = ix;
    }
  while (hi - lo > 1);

  result = (!strncmp (month, monthtab[lo].name, strlen (monthtab[lo].name))
            ? monthtab[lo].val : 0);

  return result;
}

/* Compare two lines A and B trying every key in sequence until there
   are no more keys or a difference is found. */

static int
keycompare (const struct line *a, const struct line *b)
{
  struct keyfield *key = keylist;
  char *i ;

  /* For the first iteration only, the key positions have been
     precomputed for us. */
  register char *texta = a->keybeg;
  register char *textb = b->keybeg;
  register char *lima = a->keylim;
  register char *limb = b->keylim;

  int diff;

  for (;;)
    {
      register unsigned char *translate = (unsigned char *) key->translate;
      register int *ignore = key->ignore;

      /* Find the lengths. */
      size_t lena = lima <= texta ? 0 : lima - texta;
      size_t lenb = limb <= textb ? 0 : limb - textb;

      if (key->skipeblanks)
        {
          char *a_end = texta + lena;
          char *b_end = textb + lenb;
          trim_trailing_blanks (texta, &a_end);
          trim_trailing_blanks (textb, &b_end);
          lena = a_end - texta;
          lenb = b_end - textb;
        }

      /* Actually compare the fields. */
      if (key->numeric | key->general_numeric)
        {
          char savea = *lima, saveb = *limb;

          *lima = *limb = '\0';
          diff = ((key->numeric ? numcompare : general_numcompare)
                  (texta, textb));
          *lima = savea, *limb = saveb;
        }
      else if (key->month)
        diff = getmonth (texta, lena) - getmonth (textb, lenb);
      /* Sorting like this may become slow, so in a simple locale the user
         can select a faster sort that is similar to ascii sort  */
      else if (HAVE_SETLOCALE && hard_LC_COLLATE)
        {
          if (ignore || translate)
            {
              char *copy_a = (char *) alloca (lena + 1 + lenb + 1);
              char *copy_b = copy_a + lena + 1;
              size_t new_len_a, new_len_b, i;

              /* Ignore and/or translate chars before comparing.  */
              for (new_len_a = new_len_b = i = 0; i < max (lena, lenb); i++)
                {
                  if (i < lena)
                    {
                      copy_a[new_len_a] = (translate
                                           ? translate[UCHAR (texta[i])]
                                           : texta[i]);
                      if (!ignore || !ignore[UCHAR (texta[i])])
                        ++new_len_a;
                    }
                  if (i < lenb)
                    {
                      copy_b[new_len_b] = (translate
                                           ? translate[UCHAR (textb[i])]
                                           : textb [i]);
                      if (!ignore || !ignore[UCHAR (textb[i])])
                        ++new_len_b;
                    }
                }

              diff = xmemcoll (copy_a, new_len_a, copy_b, new_len_b);
            }
          else if (lena == 0)
            diff = - NONZERO (lenb);
          else if (lenb == 0)
            goto greater;
          else
            diff = xmemcoll (texta, lena, textb, lenb);
        }
      else if (ignore)
        {
#define CMP_WITH_IGNORE(A, B)                                           \
  do                                                                    \
    {                                                                   \
          for (;;)                                                      \
            {                                                           \
              while (texta < lima && ignore[UCHAR (*texta)])            \
                ++texta;                                                \
              while (textb < limb && ignore[UCHAR (*textb)])            \
                ++textb;                                                \
              if (! (texta < lima && textb < limb))                     \
                break;                                                  \
              diff = UCHAR (A) - UCHAR (B);                             \
              if (diff)                                                 \
                goto not_equal;                                         \
              ++texta;                                                  \
              ++textb;                                                  \
            }                                                           \
                                                                        \
          diff = (texta < lima) - (textb < limb);                       \
    }                                                                   \
  while (0)

          if (translate)
            CMP_WITH_IGNORE (translate[UCHAR (*texta)],
                             translate[UCHAR (*textb)]);
          else
            CMP_WITH_IGNORE (UCHAR (*texta), UCHAR (*textb));
        }
      else if (lena == 0)
        diff = - NONZERO (lenb);
      else if (lenb == 0)
        goto greater;
      else
        {
          if (translate)
            {
              while (texta < lima && textb < limb)
                {
                  diff = (UCHAR (translate[UCHAR (*texta++)])
                          - UCHAR (translate[UCHAR (*textb++)]));
                  if (diff)
                    goto not_equal;
                }
            }
          else
            {
              diff = memcmp (texta, textb, min (lena, lenb));
              if (diff)
                goto not_equal;
            }
          diff = lena < lenb ? -1 : lena != lenb;
        }

      if (diff)
        goto not_equal;

      key = key->next;
      if (! key)
        break;

      /* Find the beginning and limit of the next field.  */
      if (key->eword != (size_t) -1)
        lima = limfield (a, key), limb = limfield (b, key);
      else
        lima = a->text + a->length - 1, limb = b->text + b->length - 1;

      if (key->sword != (size_t) -1)
        texta = begfield (a, key), textb = begfield (b, key);
      else
        {
          texta = a->text, textb = b->text;
          if (key->skipsblanks)
            {
              while (texta < lima && blanks[UCHAR (*texta)])
                ++texta;
              while (textb < limb && blanks[UCHAR (*textb)])
                ++textb;
            }
        }
    }

  return 0;

 greater:
  diff = 1;
 not_equal:
  return key->reverse ? -diff : diff;
}

static void
write_line (FILE *fp, struct line *line, char const *file)
{
  if (fwrite (line->text, line->length, 1, fp) < 1)
    die (_("write failed"), file);
}

/* Search STRING in FILE using linear search starting at offset FRONT. Use
   BUF as a temporary in-memory buffer, increasing its size if needed
*/
static void
linear_search (struct line const *line,
               FILE *fp,
               char const *file,
               off_t front,
               struct line_buffer *buf)
{
  FILE *ofp ;
  int comp ;
  size_t buf_used = 0 ;

  ofp = xfopen (output_file, "w") ;

  if (fseeko (fp, front, SEEK_SET) < 0)
    die (_("seek failed"), file);

  for (;;)
    {
      char *ptr = buf->buf + buf_used ;
      size_t readsize = (buf->buf + (buf->alloc - 2)) - ptr ;
      size_t bytes_read = fread (ptr, 1, readsize, fp) ;
      char *ptrlim = ptr + bytes_read ;
      char *p ;

      if (bytes_read != readsize)
        {
          if (ferror (fp))
            die (_("read failed"), file) ;
          if (feof (fp))
            {
              if (buf->buf == ptrlim)
                goto done ;
              if (ptrlim[-1] != eolchar)
                *ptrlim++ = eolchar ;
            }
        }

      if ((p = memchr (ptr, eolchar, ptrlim - ptr)))
        {
          make_line (&buf->line, buf->buf, p) ;
          ptr = p+1 ;
          if (0 < (comp = keycompare (&buf->line, line)))
            goto done ;
          else
            if (0 == comp)
              {
                write_line (ofp, &buf->line, output_file) ;
              }

          /* ptr now points to the start of next line */
          while ((p = memchr (ptr, eolchar, ptrlim - ptr)))
            {
              make_line (&buf->line, ptr, p) ;
              ptr = p+1 ;
              if (0 < (comp = keycompare (&buf->line, line)))
                goto done ;
              else
                if (0 == comp)
                  {
                    write_line (ofp, &buf->line, output_file) ;
                  }
            }
          fseeko (fp, (ptr-ptrlim), SEEK_CUR) ;
          ptr = buf->buf ;
        }
      else
        {
          buf_used = ptrlim - buf->buf ;

          /* The current input line is too long to fit in the buffer.
             Double the buffer size and try again.  */
          if (2 * buf->alloc < buf->alloc)
            xalloc_die ();
          buf->alloc *= 2;
          buf->buf = xrealloc (buf->buf, buf->alloc);
        }
    }

done:
  xfclose (ofp, output_file) ;
  return ;
}

/* Search a line matching LINE in FILE using binary search 
 * Invariants:
 *      front points to the the beginning of a line at or before the first
 *      matching line.
 *
 *      back points to the beginning of a line at or after the first matching
 *      line.
 *
 * Base of the Invariants:
 *      front = NULL ;
 *      back = EOF ;
 *
 * Advancing the Invariants:
 *
 *      median = first newline after halfway point from front to back
 *
 *      If the string at "median" is not greater than the string to match,
 *      median is the new front. Otherwise it is the new back.
 *
 * Termination:
 *
 *      The binary search procedure exits if front==back and hence a matching
 *      line could not be found.
 *      It lends way to linear_search if "median" equals "back". This implies
 *      that there exists a string at least half as long as (back-front),
 *      which implies that a linear search will be no more expensive than
 *      the cost of simply printing a string or two.
 *
 *      Trying to continue with binary search at this point will be more
 *      trouble than it's worth.
 *
 *      This algorithm was inspired by the look utility available as part
 *      of GNU bsdadminutils package.
 */

static void
binary_search (struct line const *line, char const *file) {
  struct line_buffer buf ;
  static size_t disk_read_size = 0 ;
  FILE *fp = xfopen (file, "r");
  struct stat st ;
  off_t front, back, median ;

  disk_read_size = max(DISK_SECTOR_SIZE, default_line_size) ;
  init_line_buffer (&buf, disk_read_size) ;

  front = 0;

  fstat (fileno (fp), &st) ;
  if (!S_ISREG(st.st_mode)) {
    linear_search (line, fp, file, front, &buf) ;
    goto done ;
  }

  back = st.st_size ;

  for (;;) {
    if (front==back)
      goto done ;

    median = front + (back-front)/2 ;

    if (((median = get_closest_line (&buf, median, fp, file)) < 0)
        || (median == back))
    {
      linear_search (line, fp, file, front, &buf) ;
      goto done ;
    }

    if (0 > keycompare (&buf.line, line))
      front = median ;
    else
      back = median ;
  }

done:
  xfclose (fp, file) ;
  free (buf.buf) ;
  return ;
}


/* Insert key KEY at the end of the key list.  */

static void
insertkey (struct keyfield *key)
{
  struct keyfield **p;

  for (p = &keylist; *p; p = &(*p)->next)
    continue;
  *p = key;
  key->next = NULL;
}

/* Report a bad field specification SPEC, with extra info MSGID.  */

static void badfieldspec (char const *, char const *)
     ATTRIBUTE_NORETURN;
static void
badfieldspec (char const *spec, char const *msgid)
{
  error (SEARCH_FAILURE, 0, _("%s: invalid field specification `%s'"),
         _(msgid), spec);
  abort ();
}

/* Parse the leading integer in STRING and store the resulting value
   (which must fit into size_t) into *VAL.  Return the address of the
   suffix after the integer.  If MSGID is NULL, return NULL after
   failure; otherwise, report MSGID and exit on failure.  */

static char const *
parse_field_count (char const *string, size_t *val, char const *msgid)
{
  char *suffix;
  uintmax_t n;

  switch (xstrtoumax (string, &suffix, 10, &n, ""))
    {
    case LONGINT_OK:
    case LONGINT_INVALID_SUFFIX_CHAR:
      *val = n;
      if (*val == n)
        break;
      /* Fall through.  */
    case LONGINT_OVERFLOW:
      if (msgid)
        error (SEARCH_FAILURE, 0, _("%s: count `%.*s' too large"),
               _(msgid), (int) (suffix - string), string);
      return NULL;

    case LONGINT_INVALID:
      if (msgid)
        error (SEARCH_FAILURE, 0, _("%s: invalid count at start of `%s'"),
               _(msgid), string);
      return NULL;
    }

  return suffix;
}

/* Handle interrupts and hangups. */

static void
sighandler (int sig)
{
#ifndef SA_NOCLDSTOP
  signal (sig, SIG_IGN);
#endif

#ifdef SA_NOCLDSTOP
  {
    struct sigaction sigact;

    sigact.sa_handler = SIG_DFL;
    sigemptyset (&sigact.sa_mask);
    sigact.sa_flags = 0;
    sigaction (sig, &sigact, NULL);
  }
#else
  signal (sig, SIG_DFL);
#endif

  raise (sig);
}

/* Set the ordering options for KEY specified in S.
   Return the address of the first character in S that
   is not a valid ordering option.
   BLANKTYPE is the kind of blanks that 'b' should skip. */

static char *
set_ordering (register const char *s, struct keyfield *key,
              enum blanktype blanktype)
{
  while (*s)
    {
      switch (*s)
        {
        case 'b':
          if (blanktype == bl_start || blanktype == bl_both)
            key->skipsblanks = 1;
          if (blanktype == bl_end || blanktype == bl_both)
            key->skipeblanks = 1;
          break;
        case 'd':
          key->ignore = nondictionary;
          break;
        case 'f':
          key->translate = fold_toupper;
          break;
        case 'g':
          key->general_numeric = 1;
          break;
        case 'i':
          key->ignore = nonprinting;
          break;
        case 'M':
          key->month = 1;
          break;
        case 'n':
          key->numeric = 1;
          break;
        case 'r':
          key->reverse = 1;
          break;
        default:
          return (char *) s;
        }
      ++s;
    }
  return (char *) s;
}

static struct keyfield *
new_key (void)
{
  struct keyfield *key = (struct keyfield *) xcalloc (1, sizeof *key);
  key->eword = -1;
  return key;
}

int
main (int argc, char **argv)
{
  struct keyfield *key;
  struct keyfield gkey;
  char const *s;
  int c = 0;
  int nfiles = 0 ;
  int posix_pedantic = (getenv ("POSIXLY_CORRECT") != NULL);
  bool obsolete_usage = (posix2_version () < 200112);
  char const *short_options = (obsolete_usage
                               ? COMMON_SHORT_OPTIONS "y::"
                               : COMMON_SHORT_OPTIONS "y:");
  char *minus = "-", *file;
  static int const sigs[] = { SIGHUP, SIGINT, SIGPIPE, SIGTERM };
  unsigned nsigs = sizeof sigs / sizeof *sigs;
#ifdef SA_NOCLDSTOP
  struct sigaction oldact, newact;
#endif
  char *string ;

  output_file = minus;
  program_name = argv[0];
  setlocale (LC_ALL, "");
  bindtextdomain (PACKAGE, LOCALEDIR);
  textdomain (PACKAGE);

  hard_LC_COLLATE = hard_locale (LC_COLLATE);
#if HAVE_NL_LANGINFO
  hard_LC_TIME = hard_locale (LC_TIME);
#endif

#if HAVE_SETLOCALE
  /* Let's get locale's representation of the decimal point */
  {
    struct lconv *lconvp = localeconv ();

    /* If the locale doesn't define a decimal point, or if the decimal
       point is multibyte, use the C decimal point.  We don't support
       multibyte decimal points yet.  */
    decimal_point = *lconvp->decimal_point;
    if (! decimal_point || lconvp->decimal_point[1])
      decimal_point = C_DECIMAL_POINT;

    /* We don't support multibyte thousands separators yet.  */
    th_sep = *lconvp->thousands_sep;
    if (! th_sep || lconvp->thousands_sep[1])
      th_sep = CHAR_MAX + 1;
  }
#endif

  have_read_stdin = 0;
  inittables ();

  /* Change the way library functions fail.  */
  xalloc_exit_failure = SEARCH_FAILURE;
  xmemcoll_exit_failure = SEARCH_FAILURE;

#ifdef SA_NOCLDSTOP
  {
    unsigned i;
    sigemptyset (&caught_signals);
    for (i = 0; i < nsigs; i++)
      sigaddset (&caught_signals, sigs[i]);
    newact.sa_handler = sighandler;
    newact.sa_mask = caught_signals;
    newact.sa_flags = 0;
  }
#endif

  {
    unsigned i;
    for (i = 0; i < nsigs; i++)
      {
        int sig = sigs[i];
#ifdef SA_NOCLDSTOP
        sigaction (sig, NULL, &oldact);
        if (oldact.sa_handler != SIG_IGN)
          sigaction (sig, &newact, NULL);
#else
        if (signal (sig, SIG_IGN) != SIG_IGN)
          signal (sig, sighandler);
#endif
      }
  }

  /*By default, compare the first field skipping leading and trailing blanks*/
  gkey.sword = -1 ; gkey.schar = 0 ;
  gkey.eword = 1 ; gkey.echar = 0 ;
  gkey.ignore = NULL;
  gkey.translate = NULL;
  gkey.numeric = gkey.general_numeric = gkey.month = gkey.reverse = 0;
  gkey.skipsblanks = gkey.skipeblanks = 1;

  for (;;)
    {
      /* Parse an operand as a file after "--" was seen; or if
         pedantic and a file was seen, unless the POSIX version
         predates 1003.1-2001 and -c was not seen and the operand is
         "-o FILE" or "-oFILE".  */

      if (c == -1
          || (posix_pedantic && nfiles != 0
              && ! (obsolete_usage
                    && optind != argc
                    && argv[optind][0] == '-' && argv[optind][1] == 'o'
                    && (argv[optind][2] || optind + 1 != argc)))
          || ((c = getopt_long (argc, argv, short_options,
                                long_options, NULL))
              == -1))
        {
          if (optind == argc)
            usage (SEARCH_FAILURE);
          string = argv[optind++] ;
          if (optind == argc)
            break;
          nfiles = 1 ;
          file = argv[optind++];
            break;
        }
      else switch (c)
        {
        case 'b':
        case 'd':
        case 'f':
        case 'g':
        case 'i':
        case 'M':
        case 'n':
        case 'r':
          {
            char str[2];
            str[0] = c;
            str[1] = '\0';
            set_ordering (str, &gkey, bl_both);
          }
          break;

        case 'k':
          key = new_key ();

          /* Get POS1. */
          s = parse_field_count (optarg, &key->sword,
                                 N_("invalid number at field start"));
          if (! key->sword--)
            {
              /* Provoke with `sort -k0' */
              badfieldspec (optarg, N_("field number is zero"));
            }
          if (*s == '.')
            {
              s = parse_field_count (s + 1, &key->schar,
                                     N_("invalid number after `.'"));
              if (! key->schar--)
                {
                  /* Provoke with `sort -k1.0' */
                  badfieldspec (optarg, N_("character offset is zero"));
                }
            }
          if (! (key->sword | key->schar))
            key->sword = -1;
          s = set_ordering (s, key, bl_start);
          if (*s != ',')
            {
              key->eword = -1;
              key->echar = 0;
            }
          else
            {
              /* Get POS2. */
              s = parse_field_count (s + 1, &key->eword,
                                     N_("invalid number after `,'"));
              if (! key->eword--)
                {
                  /* Provoke with `sort -k1,0' */
                  badfieldspec (optarg, N_("field number is zero"));
                }
              if (*s == '.')
                s = parse_field_count (s + 1, &key->echar,
                                       N_("invalid number after `.'"));
              else
                {
                  /* `-k 2,3' is equivalent to `+1 -3'.  */
                  key->eword++;
                }
              s = set_ordering (s, key, bl_end);
            }
          if (*s)
            badfieldspec (optarg, N_("stray character in field spec"));
          insertkey (key);
          break;

        case 'o':
          output_file = optarg;
          break;

        case 'L':
          specify_line_size (optarg);
          break;

        case 't':
          tab = optarg[0];
          if (tab && optarg[1])
            {
              /* Provoke with `sort -txx'.  Complain about
                 "multi-character tab" instead of "multibyte tab", so
                 that the diagnostic's wording does not need to be
                 changed once multibyte characters are supported.  */
              error (SEARCH_FAILURE, 0, _("multi-character tab `%s'"), optarg);
            }
          break;

        case 'y':
          /* Accept and ignore e.g. -y0 for compatibility with Solaris
             2.x through Solaris 7.  -y is marked as obsolete starting
             with Solaris 8.  */
          break;

        case 'z':
          eolchar = 0;
          break;

        case_GETOPT_HELP_CHAR;

        case_GETOPT_VERSION_CHAR (PROGRAM_NAME, AUTHORS);

        default:
          usage (SEARCH_FAILURE);
        }
    }

  /* Inheritance of global options to individual keys. */
  for (key = keylist; key; key = key->next)
    if (!key->ignore && !key->translate && !key->skipsblanks && !key->reverse
        && !key->skipeblanks && !key->month && !key->numeric
        && !key->general_numeric)
      {
        key->ignore = gkey.ignore;
        key->translate = gkey.translate;
        key->skipsblanks = gkey.skipsblanks;
        key->skipeblanks = gkey.skipeblanks;
        key->month = gkey.month;
        key->numeric = gkey.numeric;
        key->general_numeric = gkey.general_numeric;
        key->reverse = gkey.reverse;
      }

  if (!keylist)
    insertkey (&gkey);
  reverse = gkey.reverse;

  if (nfiles == 0)
    {
      nfiles = 1;
      file = minus;
    }

  struct line line ;
  make_line (&line, string, string+strlen(string)) ;
  binary_search(&line, file);

  if (have_read_stdin && fclose (stdin) == EOF)
    die (_("close failed"), "-");

  exit (EXIT_SUCCESS);
}

reply via email to

[Prev in Thread] Current Thread [Next in Thread]