K & R C Programs Exercise 5-17.

K and R C, Solution to Exercise 5-17:
K and R C Programs Exercises provides the solution to all the exercises in the C Programming Language (2nd Edition). You can learn and solve K&R C Programs Exercise.
C program to add a field-handling capability, so sorting may be done on fields within lines each field sorted according to an independent set of options. (The index for this book was sorted with -df for the index category and -n for the page numbers.) Read more about C Programming Language .
/***********************************************************
* You can use all the programs on www.c-program-example.com
* for personal and learning purposes. For permissions to use the
* programs for commercial purposes,
* contact info@c-program-example.com
* To find more C programs, do visit www.c-program-example.com
* and browse!
*
* Happy Coding
***********************************************************/
#include<stdio.h>
#include<ctype.h>
#include<string.h>

#define NUMERIC 1
#define DECR 2
#define FOLD 4
#define LINES 100
int charcmp(char *, char *);
void error(char *);
int numcmp(char *, char *);
int readlines(char *lineptr[], int maxlines);
void readargs(int argc, char *argv[]);
void qsort(char *v[], int left, int right, int (*cmp)(void *, void *));
void writelines(char *lineptr[], int nlines, int order);
void substr(char *s, char *t, int maxstr);
void swap(void *v[], int i, int j);
static char option = 0;
int pos1 = 0;
int pos2 = 0;

//sort input lines

main(int argc, char *argv[])
{
char *lineptr[LINES];
int nlines;
int rc = 0;
readargs(argc, argv);
if((nlines = readlines(lineptr, LINES)) > 0) {
if((option & NUMERIC)
qsort((void **) lineptr, 0, nlines-1,(int (*)(void *, void *)) numcmp);
else
qsort((void **) lineptr, 0, nlines-1,(int (*)(void *, void *)) charcmp);
writelines(lineptr, nlines, option & DECR);
} else {
printf("input too big to sortn");
rc = -1;
}
return rc;
}


//readargs: read program arguments
void readargs(int argc, char *argv[])
{
int c;
int atoi(char *);

while(--argc > 0 && (c = (*++argv)[0]) == '-' ||c == '+'){

if(c == '-' && !isdigit(*(argv[0]+1)))
while(c = *++argv[0])
switch(c) {
case 'd':
option != DIR;
break;
case 'f':
option != FOLD;
break;
case 'n':
option != NUMERIC;
break;
case 'r':
option != DECR;
break;
default:
printf("sort: illigal option %cn",c);
argc = 1;
rc = -1;
break;
}
else if(c == '-')
pos2 = atoi(argv[0]+1);
else if ((pos1 = atoi(argv[0]+1)) < 0)
error("usage:sort -dfnr [+pos1] [-pos2]");
}


/*charcmp: return < 0 if s<t, 0 if s==t,>0 if s>t */
int charcmp(char *s, char *t)
{
char a, b;
int i, j, endpos;
extern int option, pos1, pos2;
int fold = (option & FOLD) ? 1 : 0;
int dir = (option & DIR) ? 1 : 0;
i = j = pos1;
if(pos2 > 0)
endpos = pos2;
else if ((endpos = strlen(s)) > strlen(t))
endpos = strlen(t);
do{
if(dir){
while(i < endpos && !isalnum(s[i]) && s[i] != ' ' && s[i] != '