K & R C Programs Exercise 6-3

K and R C, Solution to Exercise 6-3:
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 Write a cross-referencer program that prints a list of all words in a document, and, for each word, a list of the line numbers on which it occurs. Remove noise words like “the”, “and,” and so on. 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 [email protected]
* To find more C programs, do visit www.c-program-example.com
* and browse!
* Original URL: http://www.c-program-example.com/2012/02/k-r-c-programs-exercise-6-3.html
* GitHub URL: https://github.com/snadahalli/cprograms/blob/master/knrc/knrc6_3.c
***********************************************************/

/** Write a cross-referencer program that prints a list of all words in a
* document, and, for each word, a list of the line numbers on which it
* occurs. Remove noise words like "the", "and," and so on.
**/

#include
#include
#include
#include

char *dupstr(char *s) {
char *p = NULL;
if(s != NULL){
p = malloc(strlen(s) + 1);
if(p) {
strcpy(p, s);
}
}
return p;
}

int i_strcmp(const char *s, const char *t) {
int diff = 0;
char cs = 0;
char ct = 0;

while(diff == 0 && *s != '' && *t != '') {
cs = tolower((unsigned char)*s);
ct = tolower((unsigned char)*t);
if(cs < ct) {
diff = -1;
}
else if(cs > ct) {
diff = 1;
}
++s;
++t;
}

if(diff == 0 && *s != *t) {
if(*s == '') {
diff = -1;
}
else {
diff = 1;
}
}

return diff;
}

struct linelist {
struct linelist *next;
int line;
};

struct wordtree {
char *word;
struct linelist *firstline;
struct wordtree *left;
struct wordtree *right;
};

void printlist(struct linelist *list) {
if(list != NULL) {
printlist(list->next);
printf("%6d ", list->line);
}
}

void printtree(struct wordtree *node) {
if(node != NULL) {
printtree(node->left);
printf("%18s ", node->word);
printlist(node->firstline);
printf("n");
printtree(node->right);
}
}

struct linelist *addlink(int line) {
struct linelist *new = malloc(sizeof *new);
if(new != NULL) {
new->line = line;
new->next = NULL;
}
return new;
}

void deletelist(struct linelist *listnode) {
if(listnode != NULL) {
deletelist(listnode->next);
free(listnode);
}
}

void deleteword(struct wordtree **node) {
struct wordtree *temp = NULL;
if(node != NULL) {
if(*node != '') {
if((*node)->right != NULL) {
temp = *node;
deleteword(&temp->right);
}
if((*node)->left != NULL) {
temp = *node;
deleteword(&temp->left);
}
if((*node)->word != NULL) {
free((*node)->word);
}
if((*node)->firstline != NULL) {
deletelist((*node)->firstline);
}
free(*node);
*node = NULL;
}
}
}

struct wordtree *addword(struct wordtree **node, char *word, int line) {
struct wordtree *wordloc = NULL;
struct linelist *newline = NULL;
struct wordtree *temp = NULL;
int diff = 0;

if(node != NULL && word != NULL) {
if(NULL == *node) {
node = malloc(sizeof **node);
if(NULL != *node) {
(*node)->left = NULL;
(*node)->right = NULL;
(*node)->word = dupstr(word);
if((*node)->word != NULL) {
(*node)->firstline = addlink(line);
if((*node)->firstline != NULL) {
wordloc = *node;
}
}
}
}
else {
diff = i_strcmp((*node)->word, word);
if(0 == diff) {

newline = addlink(line);
if(newline != NULL) {
wordloc = *node;
newline->next = (*node)->firstline;
(*node)->firstline = newline;
}
}
else if(0 < diff) {
temp = *node;
wordloc = addword(&temp->left, word, line);
}
else {
temp = *node;
wordloc = addword(&temp->right, word, line);
}
}
}

if(wordloc == NULL) {
deleteword(node);
}

return wordloc;
}


char *char_in_string(char *s, int c) {
char *p = NULL;

/* if there's no data, we'll stop */
if(s != NULL) {
if(c != '') {
while(*s != '' && *s != c) {
++s;
}
if(*s == c) {
p = s;
}
}
}
return p;
}

char *tokenise(char **s, char *delims) {
char *p = NULL;
char *q = NULL;

if(s != NULL && *s != '' && delims != NULL) {
/* pass over leading delimiters */
while(NULL != char_in_string(delims, **s)) {
++*s;
}
if(**s != '') {
q = *s + 1;
p = *s;
while(*q != '' && NULL == char_in_string(delims, *q)) {
++q;
}

*s = q + (*q != '');
*q = '';
}
}

return p;
}

int NoiseWord(char *s)
{
int found = 0;
int giveup = 0;

char *list[] = {
"a",
"an",
"and",
"be",
"but",
"by",
"he",
"I",
"is",
"it",
"off",
"on",
"she",
"so",
"the",
"they",
"you"
};

int top = sizeof list / sizeof list[0] - 1;
int bottom = 0;
int guess = top / 2;

int diff = 0;

if(s != NULL) {
while(!found && !giveup) {
diff = i_strcmp(list[guess], s);
if(0 == diff) {
found = 1;
}
else if(0 < diff) {
top = guess - 1;
}
else {
bottom = guess + 1;
}
if(top < bottom) {
giveup = 1;
}
else {
guess = (top + bottom) / 2;
}
}
}

return found;
}

char *GetLine(char *s, int n, FILE *fp) {
int c = 0;
int done = 0;
char *p = s;

while(!done && --n > 0 && (c = getc(fp)) != EOF) {
if((*p++ = c) == 'n') {
done = 1;
}
}

*p = '';
if(EOF == c && p == s) {
p = NULL;
}
else {
p = s;
}
return p;
}

#define MAXLINE 8192

int main(void) {
static char buffer[MAXLINE] = {0};
char *s = NULL;
char *word = NULL;
int line = 0;
int giveup = 0;
struct wordtree *tree = NULL;

char *delims = " tnrafv!"%^&*()_=+{}[]\|/,.<>:;#~?";

while(!giveup && GetLine(buffer, sizeof buffer, stdin) != NULL) {
++line;
s = buffer;
while(!giveup && (word = tokenise(&s, delims)) != NULL) {
if(!NoiseWord(word)) {
if(NULL == addword(&tree, word, line)) {
printf("Error adding data into memory. Giving up.n");
giveup = 1;
}
}
}
}

if(!giveup) {
printf("%18s Line Numbersn", "Word");
printtree(tree);
}

deleteword(&tree);
return 0;
}
Read more c programs
C Basic
C Strings
K and R C Programs Exercise

You can easily select the code by double clicking on the code area above.

To get regular updates on new C programs, you can Follow @c_program

You can discuss these programs on our Facebook Page. Start a discussion right now,

our page!

Share this program with your Facebook friends now! by liking it

(you can send this program to your friend using this button)

Like to get updates right inside your feed reader? Grab our feed!

To browse more C Programs visit this link

(c) www.c-program-example.com

K & R C Programs Exercise 6-2.

K and R C, Solution to Exercise 6-2:
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.
Write a C program that reads a C program and prints in alphabetical order each group of variable names that are identical in the first 6 characters, but different somewhere thereafter. Don’t count words within strings and comments. Make 6 a parameter that can be from the command line. 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 [email protected]
* 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>
#include<stdlib.h>

struct tnode {
char *word;
int match;
struct tnode *left;
struct tnode *right;
};
#define MAXWORD
#define YES 0
#define NO 0

struct tnode *addtreex(struct tnode *, char *,int, int);
void treexprint(struct tnode *);
int getword(char *,int);


main(int argc, char argv[])
{
struct tnode *root;
char word[MAXWORD];
int found = NO;
int num;

num = (--argc && (*++argv)[0] == '-') ? atoi(argv[0] +1) : 6;
root = NULL;
while(getword(word, MAXWORD) != EOF) {
if(isalpha(word[0]) && strlen(word) >= num)
root = addtreex(root, word, num, &found);
found = NO;
}
treexprint(root);
return 0;
}
struct tnode *talloc(void);
int compare(char *,struct tnode *, int, int *);
//addtreex: add a node with w, at or below p
struct tnode *addtreex(struct tnode *p, char *w,int num, int *found)
{
int cond;
if(p == NULL) {
p = talloc();
p->word = strdup(w);
p->match = *found;
p->left = p->right = NULL;
}
else if((cond = compare(w,p,num,found)) < 0)
p->left = addtreex(p->left, w, num, found);
else if(cond > 0)
p->right = addtreex(p->right, w, num, found);
return p;
}

//compare:compare words and update p->match
int compare(char *s,struct tnode *p, int num, int *found)
{
int i;
char *t = p->word;
for(i = 0; *s == *t;i++,s++,t++)
if(*s == '')
return 0;
if(i >= num) {
*found = YES;
p->match = YES;
}
return *s - *t;
}

/*treexprint: in-order print of tree p if p->match == YES */
void treexprint(struct tnode *p)
{
if(p != NULL) {
treexprint(p->left);
if(p->match)
printf("%sn",p->word);
treexprint(p->right);
}
}


//getword: get next word or character from input
int getword(char *word, int lim)
{
int c, d, comment(void), getch(void);
void ungetch(int);
char *w = word;
while(isspace(c = getch()))
;
if(c !=EOF)
*w++ = c;
if(isalpha(c) || c == '-' || c == '#'){
for(; --lim > 0; w++)
if(!isalnum(*w = getch()) && *w != '-') {
ungetch(*w);
break;
}
}
else if(c == ''' || c == '\'){
for(; --lim > 0; w++)
if(((*w = getch()) == '\')
*++w = getch();
else if(*w == c) {
w++;
break;
}else if(*w == EOF)
break;
}else if(c == '/')
if((d = getch()) == '*')
c = comment();
else
ungetch(d);
*w = '';
return c;
}

Read more c programs
C Basic
C Strings
K and R C Programs Exercise

You can easily select the code by double clicking on the code area above.

To get regular updates on new C programs, you can Follow @c_program

You can discuss these programs on our Facebook Page. Start a discussion right now,

our page!

Share this program with your Facebook friends now! by liking it

(you can send this program to your friend using this button)

Like to get updates right inside your feed reader? Grab our feed!

To browse more C Programs visit this link
(c) www.c-program-example.com

K & R C Programs Exercise 6-1.

K and R C, Solution to Exercise 6-1:
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 write a routine that properly handles underscores, string constants, comments, or preprocessor control lines.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 [email protected]
* To find more C programs, do visit www.c-program-example.com
* and browse!
*
* Happy Coding
***********************************************************/

#include<stdio.h>
#include<ctype.h>
//getword: get next word or character from input
int getword(char *word, int lim)
{
int c, d, comment(void), getch(void);
void ungetch(int);
char *w = word;
while(isspace(c = getch()))
;
if(c !=EOF)
*w++ = c;
if(isalpha(c) || c == '-' || c == '#'){
for(; --lim > 0; w++)
if(!isalnum(*w = getch()) && *w != '-') {
ungetch(*w);
break;
}
}
else if(c == ''' || c == '\'){
for( ; --lim > 0; w++)
if(((*w = getch()) == '\')
*++w = getch();
else if(*w == c) {
w++;
break;
}else if(*w == EOF)
break;
}else if(c == '/')
if((d = getch()) == '*')
c = comment();
else
ungetch(d);
*w = '';
return c;
}

//comment: skip over comment and return a character
int comment()
{
int c;
while((c = getch()) != EOF)
if(c == '*')
if((c = getch()) == '/')
break;
else
ungetch(c);
return c;
}

Read more c programs
C Basic
C Strings
K and R C Programs Exercise

You can easily select the code by double clicking on the code area above.

To get regular updates on new C programs, you can Follow @c_program

You can discuss these programs on our Facebook Page. Start a discussion right now,

our page!

Share this program with your Facebook friends now! by liking it

(you can send this program to your friend using this button)

Like to get updates right inside your feed reader? Grab our feed!

To browse more C Programs visit this link
(c) www.c-program-example.com

K & R C Programs Exercise 5-20.

K and R C, Solution to Exercise 5-20:
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 expand dcl to handle declarations with function argument types, qualifiers like const, and so on. 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 [email protected]
* To find more C programs, do visit www.c-program-example.com
* and browse!
*
* Happy Coding
***********************************************************/


#include<stdio.h>
#include<string.h>
#include<ctype.h>
enum { NAME, PARENS, BRACKETS};
enum { NO, YES};
void dcl(void);
void dirdcl(void);
void errmsg(char *);
void dclspec(void);
int typespec(void);
int typeequal(void);
int compare(char **, char**);
void parmdcl(void);

int gettoken(void);
extern int tokentype;
extern char token[];
extern char name[];
extern char datatype[];
extern char out[];
extern int prevtoken;


//dcl:parse a declarator
void dcl(void)
{
int ns;
for(ns = 0; gettoken() == '*';)
ns++;
dirdcl();
while(ns --> 0)
strcat(out, "pointer to");
}


//dirdcl: parse a direct declaration
void dirdcl(void)
{
int type;
void parmdcl(void);
if(tokentype == '('){
dcl();
if(tokentype != ')')
errmsg("error:missimg)n");
}
else if(tokentype == NAME){
if(name[0] == '')
strcpy(name,token);
}else
prevtoken = YES;
while((type = gettoken()) == PARENS || type == BRACKETS || type == '(')
if(type == PARENS)
strcat(out, "function returning");
else if(type == '('){
strcat(out, "function expecting");
parmdcl();
strcat(out, "and returning");
} else{


strcat(out, "array");
strcat(out, token);
strcat(out, "of");
}
}

//errmsg: prints the error message
void errmsg(char *msg)
{
printf("%sn",msg);
prevtoken = YES;
}


//get token:return next token
int gettoken(void)
{
int c, getch(void);
void ungetch(int);
char *p = token;
if(prevtoken == YES) {
prevtoken = NO;
return tokentype;
while((c = getch()) == ' ' || c == 't')
;
if(c == '('){
if ((c = getch()) == ')'){
strcpy(token,"()");
return tokentype = PARENS;
}
else{
ungetch(c);
return tokentype = '(';
}
}
else if(c == '['){
for(*p++ = c; (*p++ = getch()) != ']';)
;
*p = '';
return tokentype = BRACKETS;
}
else if (isalpha(c)) {
for(*p++ = c; isalnum(c = getch());)
*p++ = c;
*p = '';
ungetch(c);
return tokentype = NAME;
} else
return tokentype = c;
}



//parmdcl: parse a parameter declarator
void parmdcl(void)
{
do{
dclspec();
}while (tokentype == ',');
if(tokentype != ')')
errmsg("missing ) in parameter declarationn");
}

//dclspec: declaration specification
void dclspec(void)
{
char temp[MAXTOKEN];
temp[0] = '';
gettoken();
do{
if(tokentype != NAME){
prevtoken = YES;
dcl();
}else if(typedesc() == YES){
strcat(temp," ");
strcat(temp, token);
gettoken();
}else if(typeequal() == YES){
strcat(temp," ");
strcat(temp, token);
gettoken();
}else
errmsg("unknown type parameter listn");
}while(tokentype != ',' && tokentype != ')');
strcat(out,temp);
if(tokentype == ',');
strcat(out,",");
}

//typedesc: return yes if token is type-specifier
int typespec(void)
{
static char *types[] = {
"char",
"int",
"void"
};
char *pt = token;
if(bsearch(&pt, types,sizeof(types)/sizeof(char *),
sizeof(char *),compare) == NULL)
return NO;
else
return YES;
}

//typeequal:return YES if token is a type qualifier
int typeequal(void)
{
static char *typeq[] = {
"const",
"volatite"
};
char *pt = token;
if(bsearch(&pt, typeq,sizeof(typeq)/sizeof(char *),
sizeof(char *),compare) == NULL)
return NO;
else
return YES;

}

//compare: compare two strings for bsearch
int compare(char **s, char **s)
{
return strcmp(*s, *t);
}
Read more c programs
C Basic
C Strings
K and R C Programs Exercise

You can easily select the code by double clicking on the code area above.

To get regular updates on new C programs, you can Follow @c_program

You can discuss these programs on our Facebook Page. Start a discussion right now,

our page!

Share this program with your Facebook friends now! by liking it

(you can send this program to your friend using this button)

Like to get updates right inside your feed reader? Grab our feed!

To browse more C Programs visit this link
(c) www.c-program-example.com

K & R C Programs Exercise 5-19.

K and R C, Solution to Exercise 5-19:
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 modify(K & R C Programs Exercise 5-18.) undcl so that it does not add redundant parentheses to declarations. 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 [email protected]
* To find more C programs, do visit www.c-program-example.com
* and browse!
*
* Happy Coding
***********************************************************/

#include<stdio.h>
#include<string.h>
#include<ctype.h>

#define MAXTOKEN 100

enum { NAME, PARENS, BRACKETS};
enum { YES, NO};



int gettoken(void);
int nexttoken(void);
extern int tokentype;
extern char token[MAXTOKEN];
char out[1000];
extern int prevtoken = NO;
//UNDCL:convert word description to declaration
main()
{
int type;
char temp[MAXTOKEN];
while (gettoken() !=EOF) {
strcy(out, token);
while ((type = gettoken()) != 'n')
if(type == PARENS || type == BRACKETS)
strcat(out, token);
else if(type == '*') {
if((type = nexttoken()) == PARENS || type == BRACKETS)
sprintf(temp, "(*%s)", out);
else
sprintf(temp, "*%s", out);
strcpy(out, temp);

}else if(type == NAME){
sprintf(temp, "%s%s",token, out);
strcpy(out, temp);
}else
printf("Invalid input at %sn",token);
printf("%sn",out);
}
return 0;
}


//nexttoken: get the next token and push it back
int nexttoken(void)
{
int type;
extern int prevtoken;
type = gettoken();
prevtoken = YES;
return type;
}


//get token:return next token
int gettoken(void)
{
int c, getch(void);
void ungetch(int);
char *p = token;
if(prevtoken == YES) {
prevtoken = NO;
return tokentype;
}
while((c = getch()) == ' ' || c == 't')
;
if(c == '('){
if ((c = getch()) == ')'){
strcpy(token,"()");
return tokentype = PARENS;
}
else{
ungetch(c);
return tokentype = '(';
}
}
else if(c == '['){
for(*p++ = c; (*p++ = getch()) != ']';)
;
*p = '';
return tokentype = BRACKETS;
}
else if (isalpha(c)) {
for(*p++ = c; isalnum(c = getch());)
*p++ = c;
*p = '';
ungetch(c);
return tokentype = NAME;
} else
return tokentype = c;
}


Read more c programs
C Basic
C Strings
K and R C Programs Exercise

You can easily select the code by double clicking on the code area above.

To get regular updates on new C programs, you can Follow @c_program

You can discuss these programs on our Facebook Page. Start a discussion right now,

our page!

Share this program with your Facebook friends now! by liking it

(you can send this program to your friend using this button)

Like to get updates right inside your feed reader? Grab our feed!

To browse more C Programs visit this link
(c) www.c-program-example.com

K & R C Programs Exercise 5-18.

K and R C, Solution to Exercise 5-18:
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 convert the C declaration into a word description and Make dcl recover from input errors.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 [email protected]
* To find more C programs, do visit www.c-program-example.com
* and browse!
*
* Happy Coding
***********************************************************/

#include<stdio.h>
#include<string.h>
#include<ctype.h>
enum { NAME, PARENS, BRACKETS};
enum { NO, YES};
void dcl(void);
void dirdcl(void);
void errmsg(char *);


int gettoken(void);
extern int tokentype;
extern char token[];
extern char name[];
extern char out[];
extern int prevtoken;

main()
{
int type;
char temp[MAXTOKEN];
while (gettoken() !=EOF) {
strcy(out, token);
while ((type = gettoken()) != 'n')
if(type == PARENS || type == BRACKETS)
strcat(out, token);
else if(type == '*') {
sprintf(temp, "(*%s)", out);
strcpy(out, temp);
}else if(type == NAME){
sprintf(temp, "%s%s",token, out);
strcpy(out, temp);
}else
printf("Invalid input at %sn",token);
printf("%sn",out);
}
return 0;
}


//dcl:parse a declarator
void dcl(void)
{
int ns;
for(ns = 0; gettoken() == '*';)
ns++;
dirdcl();
while(ns --> 0)
strcat(out, "pointer to");
}


//dirdcl: parse a direct declaration
void dirdcl(void)
{
int type;
if(tokentype == '('){
dcl();
if(tokentype != ')')
errmsg("error:missimg)n");
}
else if(tokentype == NAME)
strcpy(name,token);
else
errmsg("error:expected name or (dcl)n");
while((type = gettoken()) == PARENS || type == BRACKETS)
if(type == PARENS)
strcat(out, "function returning");
else {
strcat(out, "array");
strcat(out, token);
strcat(out, "of");
}
}

//errmsg: prints the error message
void errmsg(char *msg)
{
printf("%sn",msg);
prevtoken = YES;
}


//get token:return next token
int gettoken(void)
{
int c, getch(void);
void ungetch(int);
char *p = token;
if(prevtoken == YES) {
prevtoken = NO;
return tokentype;
}
while((c = getch()) == ' ' || c == 't')
;
if(c == '('){
if ((c = getch()) == ')'){
strcpy(token,"()");
return tokentype = PARENS;
}
else{
ungetch(c);
return tokentype = '(';
}
}
else if(c == '['){
for(*p++ = c; (*p++ = getch()) != ']';)
;
*p = '';
return tokentype = BRACKETS;
}
else if (isalpha(c)) {
for(*p++ = c; isalnum(c = getch());)
*p++ = c;
*p = '';
ungetch(c);
return tokentype = NAME;
} else
return tokentype = c;
}


Read more c programs
C Basic
C Strings
K and R C Programs Exercise

You can easily select the code by double clicking on the code area above.

To get regular updates on new C programs, you can Follow @c_program

You can discuss these programs on our Facebook Page. Start a discussion right now,

our page!

Share this program with your Facebook friends now! by liking it

(you can send this program to your friend using this button)

Like to get updates right inside your feed reader? Grab our feed!

To browse more C Programs visit this link
(c) www.c-program-example.com

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 [email protected]
* 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] != '')
i++;
while(j < endpos && !isalnum(t[j]) && t[j] != ' ' && t[j] != '')
j++;
}
if(i < endpos && j < endpos) {
a = fold ? tolower(s[i]) : s[i];
i++;
b = fold ? tolower(t[j]) : t[j];
j++;
if(a == b && a == '')
return 0;
}
}while(a == b && i < endpos && j < endpos);
return a - b;

}

/* substr: get a substring of s and put in str*/
void substr(char *s, char *str)
{
int i, j, len;
extern int pos1, pos2;
len = strlen(s);
if(pos2 > 0 && len > pos2)
len = pos2;
else if(pos2 > 0 && len < pos2)
error("substr: string too shortn");
for(j = 0, i = pos1;i < len; i++, j++)
str[j] = s[i];
str[j] = '';
}

//errror: prints the error message
void error(char *s)
{
printf("%sn",s);
exit(1);
}


//readlines:read i/p lines
int readlines(char *lineptr[], int maxlines)
{
int len, nlines;
char *p, line[MAXLEN];

nlines = 0;
while ((len = getline(line, MAXLEN)) > 0)
if (nlines >= maxlines || (p = malloc(len)) == NULL)
return -1;
else {
line[len - 1] = '';
strcpy(p, line);
lineptr[nlines++] = p;
}
return nlines;
}

//writeline:write output lines
void writelines(char *lineptr[], int nlines)
{
int i;

for (i = 0; i < nlines; i++)
printf("%sn", lineptr[i]);
}


//cnumcmp:ompare p1 and p2 numerically
int numcmp(const void *p1, const void *p2)
{
char * const *s1 = reverse ? p2 : p1;
char * const *s2 = reverse ? p1 : p2;
double v1, v2;

v1 = atof(*s1);
v2 = atof(*s2);
if (v1 < v2)
return -1;
else if (v1 > v2)
return 1;
else
return 0;
}

/*qsort: sort v[left]....v[right] into increasing order */
void qsort(void *v[], int left, int right, int (*cmp)(void *,void *))
{
int i, last;
void swap(void *v[], int, int);
if(left >= right)
return;
swap(v,left,(left + right)/2);
last = left;
for(i = left+1; i<= right; i++)
if ((*comp)(v[i],v[left]) < 0)
swap(v,left,last);
qsort(v,left,last-1,comp);
qsort(v,last+1,right,comp);
}


void swap(void *v[], int i, int j)
{
void *temp;
temp = v[i];
v[i] = v[j];
v[j] = temp;
}

Read more c programs
C Basic
C Strings
K and R C Programs Exercise

You can easily select the code by double clicking on the code area above.

To get regular updates on new C programs, you can Follow @c_program

You can discuss these programs on our Facebook Page. Start a discussion right now,

our page!

Share this program with your Facebook friends now! by liking it

(you can send this program to your friend using this button)

Like to get updates right inside your feed reader? Grab our feed!

To browse more C Programs visit this link
(c) www.c-program-example.com

K & R C Programs Exercise 5-15.

K and R C, Solution to Exercise 5-15:
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 the option -f to fold upper and l;ower case together, so that case distinctions are not made during sorting; for example, c and C compare equal. 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 [email protected]
* To find more C programs, do visit www.c-program-example.com
* and browse!
*
* Happy Coding
***********************************************************/

#include<stdio.h>
#include<string.h>
#include<ctype.h>


#define NUMERIC 1
#define DECR 2
#define FOLD 4
#define LINES 100
int charcmp(char *, char *);
int numcmp(char *, char *);
int readlines(char *lineptr[], int maxlines);
void qsort(char *v[], int left, int right, int (*cmp)(void *, void *));
void write lines(char *lineptr[], int nlines, int order);
static char option = 0;
// sort input lines
main(int argc, char *argv[])
{
char *lineptr[LINES];
int nlines;
int c, rc = 0;
while(--argc > 0 && (*++argv)[0] == '-')
while(c = *++argv[0]
switch(c) {

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;
}
if(argc)
printf("Usage:sort -dfnr n");
else{
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;
}


/*charcmp: return < 0 if s<t, 0 if s==t,>0 if s>t */
int charcmp(char *s, char *t)
{
for(; tolower(*s) == tolower(*t);s++,t++)
if(*s == '')
return 0;
return tolwer(*s) - tolower(*t);
}


//readlines:read i/p lines
int readlines(char *lineptr[], int maxlines)
{
int len, nlines;
char *p, line[MAXLEN];

nlines = 0;
while ((len = getline(line, MAXLEN)) > 0)
if (nlines >= maxlines || (p = malloc(len)) == NULL)
return -1;
else {
line[len - 1] = '';
strcpy(p, line);
lineptr[nlines++] = p;
}
return nlines;
}

//writeline:write output lines
void writelines(char *lineptr[], int nlines)
{
int i;

for (i = 0; i < nlines; i++)
printf("%sn", lineptr[i]);
}


//cnumcmp:ompare p1 and p2 numerically
int numcmp(const void *p1, const void *p2)
{
char * const *s1 = reverse ? p2 : p1;
char * const *s2 = reverse ? p1 : p2;
double v1, v2;

v1 = atof(*s1);
v2 = atof(*s2);
if (v1 < v2)
return -1;
else if (v1 > v2)
return 1;
else
return 0;
}

/*qsort: sort v[left]....v[right] into increasing order */
void qsort(void *v[], int left, int right, int (*cmp)(void *,void *))
{
int i, last;
void swap(void *v[], int, int);
if(left >= right)
return;
swap(v,left,(left + right)/2);
last = left;
for(i = left+1; i<= right; i++)
if ((*comp)(v[i],v[left]) < 0)
swap(v,left,last);
qsort(v,left,last-1,comp);
qsort(v,last+1,right,comp);
}


void swap(void *v[], int i, int j)
{
void *temp;
temp = v[i];
v[i] = v[j];
v[j] = temp;
}
Read more c programs
C Basic
C Strings
K and R C Programs Exercise

You can easily select the code by double clicking on the code area above.

To get regular updates on new C programs, you can Follow @c_program

You can discuss these programs on our Facebook Page. Start a discussion right now,

our page!

Share this program with your Facebook friends now! by liking it

(you can send this program to your friend using this button)

Like to get updates right inside your feed reader? Grab our feed!

To browse more C Programs visit this link
(c) www.c-program-example.com

K & R C Programs Exercise 5-16.

K and R C, Solution to Exercise 5-16:
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 the option -d(“directory order”) option, which makes comparisons only on letters, numbers and blanks. Make sure it works in conjunction with -f. 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 [email protected]
* To find more C programs, do visit www.c-program-example.com
* and browse!
*
* Happy Coding
***********************************************************/

#include<stdio.h>
#include<string.h>
#include<ctype.h>


#define NUMERIC 1
#define DECR 2
#define FOLD 4
#define LINES 100
int charcmp(char *, char *);
int numcmp(char *, char *);
int readlines(char *lineptr[], int maxlines);
void qsort(char *v[], int left, int right, int (*cmp)(void *, void *));
void write lines(char *lineptr[], int nlines, int order);
static char option = 0;
// sort input lines
main(int argc, char *argv[])
{
char *lineptr[LINES];
int nlines;
int c, rc = 0;
while(--argc > 0 && (*++argv)[0] == '-')
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;
}
if(argc)
printf("Usage:sort -dfnr n");
else{
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;
}


/*charcmp: return < 0 if s<t, 0 if s==t,>0 if s>t */
int charcmp(char *s, char *t)
{
char a, b;
int fold = (option & FOLD) ? 1 : 0;
int dir = (option & DIR) ? 1 : 0;
do {
if (dir) {
while (!isalnum(*s) && *s != ' ' && *s != '')
s++;
while (!isalnum(*t) && *t != ' ' && *t != '')
t++;
}
a = fold ? tolower(*s) : *s;
s++;
b = fold ? tolower(*t) : *t;
t++;
if (a == b && a =='')
return 0;
}while (a == b);
return a -b;
}


//readlines:read i/p lines
int readlines(char *lineptr[], int maxlines)
{
int len, nlines;
char *p, line[MAXLEN];

nlines = 0;
while ((len = getline(line, MAXLEN)) > 0)
if (nlines >= maxlines || (p = malloc(len)) == NULL)
return -1;
else {
line[len - 1] = '';
strcpy(p, line);
lineptr[nlines++] = p;
}
return nlines;
}

//writeline:write output lines
void writelines(char *lineptr[], int nlines)
{
int i;

for (i = 0; i < nlines; i++)
printf("%sn", lineptr[i]);
}


//cnumcmp:ompare p1 and p2 numerically
int numcmp(const void *p1, const void *p2)
{
char * const *s1 = reverse ? p2 : p1;
char * const *s2 = reverse ? p1 : p2;
double v1, v2;

v1 = atof(*s1);
v2 = atof(*s2);
if (v1 < v2)
return -1;
else if (v1 > v2)
return 1;
else
return 0;
}

/*qsort: sort v[left]....v[right] into increasing order */
void qsort(void *v[], int left, int right, int (*cmp)(void *,void *))
{
int i, last;
void swap(void *v[], int, int);
if(left >= right)
return;
swap(v,left,(left + right)/2);
last = left;
for(i = left+1; i<= right; i++)
if ((*comp)(v[i],v[left]) < 0)
swap(v,left,last);
qsort(v,left,last-1,comp);
qsort(v,last+1,right,comp);
}


void swap(void *v[], int i, int j)
{
void *temp;
temp = v[i];
v[i] = v[j];
v[j] = temp;
}
Read more c programs
C Basic
C Strings
K and R C Programs Exercise

You can easily select the code by double clicking on the code area above.

To get regular updates on new C programs, you can Follow @c_program

You can discuss these programs on our Facebook Page. Start a discussion right now,

our page!

Share this program with your Facebook friends now! by liking it

(you can send this program to your friend using this button)

Like to get updates right inside your feed reader? Grab our feed!

To browse more C Programs visit this link
(c) www.c-program-example.com

K & R C Programs Exercise 5-14.

K and R C, Solution to Exercise 5-14:
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.
Write a C program to handle a -r flag which indicates sorting in reverse (decreasing) order. But sure that -r works with -n.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 [email protected]
* To find more C programs, do visit www.c-program-example.com
* and browse!
*
* Happy Coding
***********************************************************/

#include <stdio.h>
#include <string.h>
#include <stdlib.h>

#define TRUE 1
#define FALSE 0

#define MAXLINES 5000
char *lineptr[MAXLINES];

#define MAXLEN 1000

int reverse = FALSE;

int getline(char s[], int lim)
{
int c, i;

for (i = 0; i < lim - 1 && (c = getchar()) != EOF && c != 'n'; i++)
s[i] = c;
if (c == 'n') {
s[i++] = c;
}
s[i] = '';
return i;
}


int readlines(char *lineptr[], int maxlines)
{
int len, nlines;
char *p, line[MAXLEN];

nlines = 0;
while ((len = getline(line, MAXLEN)) > 0)
if (nlines >= maxlines || (p = malloc(len)) == NULL)
return -1;
else {
line[len - 1] = '';
strcpy(p, line);
lineptr[nlines++] = p;
}
return nlines;
}


void writelines(char *lineptr[], int nlines)
{
int i;

for (i = 0; i < nlines; i++)
printf("%sn", lineptr[i]);
}

int pstrcmp(const void *p1, const void *p2)
{
char * const *s1 = reverse ? p2 : p1;
char * const *s2 = reverse ? p1 : p2;

return strcmp(*s1, *s2);
}

int numcmp(const void *p1, const void *p2)
{
char * const *s1 = reverse ? p2 : p1;
char * const *s2 = reverse ? p1 : p2;
double v1, v2;

v1 = atof(*s1);
v2 = atof(*s2);
if (v1 < v2)
return -1;
else if (v1 > v2)
return 1;
else
return 0;
}

int main(int argc, char *argv[])
{
int nlines;
int numeric = FALSE;
int i;

for (i = 1; i < argc; i++) {
if (*argv[i] == '-') {
switch (*(argv[i] + 1)) {
case 'n': numeric = TRUE; break;
case 'r': reverse = TRUE; break;
default:
fprintf(stderr, "invalid switch '%s'n", argv[i]);
return EXIT_FAILURE;
}
}
}

if ((nlines = readlines(lineptr, MAXLINES)) >= 0) {
qsort(lineptr, nlines, sizeof(*lineptr), numeric ? numcmp : pstrcmp);
writelines(lineptr, nlines);
return EXIT_SUCCESS;
} else {
fputs("input too big to sortn", stderr);
return EXIT_FAILURE;
}
}


Read more c programs 
C Basic
C Strings
K and R C Programs Exercise

You can easily select the code by double clicking on the code area above.

To get regular updates on new C programs, you can Follow @c_program

You can discuss these programs on our Facebook Page. Start a discussion right now,

our page!

Share this program with your Facebook friends now! by liking it

(you can send this program to your friend using this button)

Like to get updates right inside your feed reader? Grab our feed!

To browse more C Programs visit this link
(c) www.c-program-example.com