Chapter 13
#include
#include
//#include
int main(int argc, char *argv[])
{
int byte;
FILE * source;
FILE * target;
// argc = ccommand(&argv);
if (argc != 3)
{
printf("Usage: %s sourcefile targetfile\n", argv[0]);
exit(EXIT_FAILURE);
}
if ((source = fopen(argv[1], "rb")) == NULL)
{
printf("Could not open file %s for input\n", argv[1]);
exit(EXIT_FAILURE);
}
if ((target = fopen(argv[2], "wb")) == NULL)
{
printf("Could not open file %s for output\n", argv[2]);
exit(EXIT_FAILURE);
}
while ((byte = getc(source)) != EOF)
{
putc(byte, target);
}
if (fclose(source) != 0)
printf("Could not close file %s\n", argv[1]);
if (fclose(target) != 0)
printf("Could not close file %s\n", argv[2]);
return 0;
}
#include
#include
#include
int main(int argc, char *argv[])
{
int byte;
FILE * source;
int filect;
argc = ccommand(&argv);
if (argc == 1)
{
printf("Usage: %s filename[s]\n", argv[0]);
exit(EXIT_FAILURE);
}
for (filect = 1; filect < argc; filect++)
{
if ((source = fopen(argv[filect], "r")) == NULL)
{
printf("Could not open file %s for input\n", argv[filect]);
continue;
}
while ((byte = getc(source)) != EOF)
{
putchar(byte);
}
if (fclose(source) != 0)
printf("Could not close file %s\n", argv[1]);
}
return 0;
}
#include
#include
#include
//#include
#define BUFSIZE 1024
#define SLEN 81
void append(FILE *source, FILE *dest);
int main(int argc, char *argv[])
{
FILE *fa, *fs;
int files = 0;
int fct;
// argc = ccommand(&argv);
if (argc < 3)
{
printf("Usage: %s appendfile sourcefile[s]\n", argv[0]);
exit(EXIT_FAILURE);
}
if ((fa = fopen(argv[1], "a")) == NULL)
{
fprintf(stderr, "Can't open %s\n", argv[1]);
exit(EXIT_FAILURE);
}
if (setvbuf(fa, NULL, _IOFBF, BUFSIZE) != 0)
{
fputs("Can't create output buffer\n", stderr);
exit(EXIT_FAILURE);
}
for (fct = 2; fct < argc; fct++)
{
if (strcmp(argv[fct], argv[1]) == 0)
fputs("Can't append file to itself\n",stderr);
else if ((fs = fopen(argv[fct], "r")) == NULL)
fprintf(stderr, "Can't open %s\n", argv[fct]);
else
{
if (setvbuf(fs, NULL, _IOFBF, BUFSIZE) != 0)
{
fputs("Can't create output buffer\n",stderr);
continue;
}
append(fs, fa);
if (ferror(fs) != 0)
fprintf(stderr,"Error in reading file %s.\n",
argv[fct]);
if (ferror(fa) != 0)
fprintf(stderr,"Error in writing file %s.\n",
argv[1]);
fclose(fs);
files++;
printf("File %s appended.\n", argv[fct]);
}
}
printf("Done. %d files appended.\n", files);
fclose(fa);
return 0;
}
void append(FILE *source, FILE *dest)
{
size_t bytes;
static char temp[BUFSIZE]; // allocate once
while ((bytes = fread(temp,sizeof(char),BUFSIZE,source)) > 0)
fwrite(temp, sizeof (char), bytes, dest);
}
#include
#include
#include
int main(int argc, char *argv[])
{
int ch1, ch2;
FILE * f1;
FILE * f2;
argc = ccommand(&argv);
if (argc != 3)
{
printf("Usage: %s file1 file2\n", argv[0]);
exit(EXIT_FAILURE);
}
if ((f1 = fopen(argv[1], "r")) == NULL)
{
printf("Could not open file %s for input\n", argv[1]);
exit(EXIT_FAILURE);
}
if ((f2 = fopen(argv[2], "r")) == NULL)
{
printf("Could not open file %s for input\n", argv[2]);
exit(EXIT_FAILURE);
}
ch1 = getc(f1);
ch2 = getc(f2);
while (ch1 != EOF || ch2 != EOF)
{
while (ch1 != EOF && ch1 != '\n')
{
putchar(ch1);
ch1 = getc(f1);
}
if (ch1 != EOF)
{
putchar('\n');
ch1 = getc(f1);
}
while (ch2 != EOF && ch2 != '\n')
{
putchar(ch2);
ch2 = getc(f2);
}
if (ch2 != EOF)
{
putchar('\n');
ch2 = getc(f2);
}
}
if (fclose(f1) != 0)
printf("Could not close file %s\n", argv[1]);
if (fclose(f2) != 0)
printf("Could not close file %s\n", argv[2]);
return 0;
}
#include
#include
#include
int main(int argc, char *argv[])
{
int ch1, ch2;
FILE * f1;
FILE * f2;
argc = ccommand(&argv);
if (argc != 3)
{
printf("Usage: %s file1 file2\n", argv[0]);
exit(EXIT_FAILURE);
}
if ((f1 = fopen(argv[1], "r")) == NULL)
{
printf("Could not open file %s for input\n", argv[1]);
exit(EXIT_FAILURE);
}
if ((f2 = fopen(argv[2], "r")) == NULL)
{
printf("Could not open file %s for input\n", argv[2]);
exit(EXIT_FAILURE);
}
ch1 = getc(f1);
ch2 = getc(f2);
while (ch1 != EOF || ch2 != EOF)
{
while (ch1 != EOF && ch1 != '\n')
{
putchar(ch1);
ch1 = getc(f1);
}
if (ch1 != EOF)
{
if (ch2 == EOF)
putchar('\n');
else
putchar(' ');
ch1 = getc(f1);
}
while (ch2 != EOF && ch2 != '\n')
{
putchar(ch2);
ch2 = getc(f2);
}
if (ch2 != EOF)
{
putchar('\n');
ch2 = getc(f2);
}
}
if (fclose(f1) != 0)
printf("Could not close file %s\n", argv[1]);
if (fclose(f2) != 0)
printf("Could not close file %s\n", argv[2]);
return 0;
}
#include
#include
#define MAX 40
int main(void)
{
FILE *fp;
char words[MAX];
int wordct = 0;
if ((fp = fopen("wordy", "a+")) == NULL)
{
fprintf(stderr,"Can't open \"words\" file.\n");
exit(1);
}
rewind(fp);
while (fgets(words, MAX - 1, fp) != NULL)
wordct++;
rewind(fp);
puts("Enter words to add to the file. Enter one word per line, and ");
puts("press the Enter key at the beginning of a line to terminate.");
while (gets(words) != NULL && words[0] != '\0')
fprintf(fp, "%d: %s\n", ++wordct, words);
puts("File contents:");
rewind(fp);
while (fgets(words, MAX - 1, fp) != NULL)
fputs(words, stdout);
if (fclose(fp) != 0)
fprintf(stderr,"Error closing file\n");
return 0;
}
#include
#include
#include
#define SLEN 256
const char *errmesg[] = {"Usage: %s string filename]\n",
"Can't open file %s\n" };
int main(int argc, char *argv[])
{
FILE *fp;
char line[SLEN];
argc = ccommand(&argv);
if (argc != 3)
{
fprintf(stderr, errmesg[0], argv[0]);
exit(EXIT_FAILURE);
}
if ((fp = fopen(argv[2], "r")) == NULL)
{
fprintf(stderr, errmesg[1], argv[2]);
exit(EXIT_FAILURE);
}
while (fgets(line, SLEN - 1, fp) != NULL)
{
if (strstr(line, argv[1]) != NULL)
fputs(line, stdout);
}
fclose(fp);
return 0;
}
Data for program:
0 0 9 0 0 0 0 0 0 0 0 0 5 8 9 9 8 5 2 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 9 0 0 0 0 0 0 0 5 8 9 9 8 5 5 2 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 5 8 1 9 8 5 4 5 2 0 0 0 0 0 0 0 0 0
0 0 0 0 9 0 0 0 0 0 0 0 5 8 9 9 8 5 0 4 5 2 0 0 0 0 0 0 0 0
0 0 9 0 0 0 0 0 0 0 0 0 5 8 9 9 8 5 0 0 4 5 2 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 5 8 9 1 8 5 0 0 0 4 5 2 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 5 8 9 9 8 5 0 0 0 0 4 5 2 0 0 0 0 0
5 5 5 5 5 5 5 5 5 5 5 5 5 8 9 9 8 5 5 5 5 5 5 5 5 5 5 5 5 5
8 8 8 8 8 8 8 8 8 8 8 8 5 8 9 9 8 5 8 8 8 8 8 8 8 8 8 8 8 8
9 9 9 9 0 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 3 9 9 9 9 9 9 9
8 8 8 8 8 8 8 8 8 8 8 8 5 8 9 9 8 5 8 8 8 8 8 8 8 8 8 8 8 8
5 5 5 5 5 5 5 5 5 5 5 5 5 8 9 9 8 5 5 5 5 5 5 5 5 5 5 5 5 5
0 0 0 0 0 0 0 0 0 0 0 0 5 8 9 9 8 5 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 5 8 9 9 8 5 0 0 0 0 6 6 0 0 0 0 0 0
0 0 0 0 2 2 0 0 0 0 0 0 5 8 9 9 8 5 0 0 5 6 0 0 6 5 0 0 0 0
0 0 0 0 3 3 0 0 0 0 0 0 5 8 9 9 8 5 0 5 6 1 1 1 1 6 5 0 0 0
0 0 0 0 4 4 0 0 0 0 0 0 5 8 9 9 8 5 0 0 5 6 0 0 6 5 0 0 0 0
0 0 0 0 5 5 0 0 0 0 0 0 5 8 9 9 8 5 0 0 0 0 6 6 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 5 8 9 9 8 5 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 5 8 9 9 8 5 0 0 0 0 0 0 0 0 0 0 0 0
#include
#include
#define ROWS 20
#define COLS 30
#define LEVELS 10
const char trans[LEVELS + 1] = " .':~*=&%@";
void MakePic(int data[][COLS], char pic[][COLS], int rows);
void init(char arr[][COLS], char ch);
int main()
{
int row, col;
int picIn[ROWS][COLS];
char picOut[ROWS][COLS];
char fileName[40];
FILE * infile;
init(picOut, 'S');
printf("Enter name of file: ");
scanf("%s", fileName);
if ((infile = fopen(fileName, "r")) == NULL)
{
fprintf(stderr, "Could not open data file.\n");
exit(EXIT_FAILURE);
}
for (row = 0; row < ROWS; row++)
for (col = 0; col < COLS; col++)
fscanf(infile, "%d", &picIn[row][col]);
if (ferror(infile))
{
fprintf(stderr, "Error getting data from file.\n");
exit(EXIT_FAILURE);
}
MakePic(picIn, picOut, ROWS);
for (row = 0; row < ROWS; row++)
{
for (col = 0; col < COLS; col++)
putchar(picOut[row][col]);
putchar('\n');
}
return 0;
}
void init(char arr[][COLS], char ch)
{
int r, c;
for (r = 0; r < ROWS; r++)
for (c = 0; c < COLS; c++)
arr[r][c] = ch;
}
void MakePic(int data[][COLS], char pic[][COLS], int rows)
{
int row, col;
for (row = 0; row < rows; row++)
for (col = 0; col < COLS; col++)
pic[row][col] = trans[data[row][col]];
}
Chapter 14
#include
#include
#include
struct month {
char name[10];
char abbrev[4];
int days;
int monumb;
};
const struct month months[12] = {
{"January", "Jan", 31, 1},
{"February", "Feb", 28, 2},
{"March", "Mar", 31, 3},
{"April", "Apr", 30, 4},
{"May", "May", 31, 5},
{"June", "Jun", 30, 6},
{"July", "Jul", 31, 7},
{"August", "Aug", 31, 8},
{"September", "Sep", 30, 9},
{"October", "Oct", 31, 10},
{"November", "Nov", 30, 11},
{"December", "Dec", 31, 12}
};
int days(char * m);
int main(void)
{
char input[20];
int daytotal;
printf("Enter the name of a month: ");
while (gets(input) != NULL && input[0] != '\0')
{
daytotal = days(input);
if (daytotal > 0)
printf("There are %d days through %s.\n", daytotal, input);
else
printf("%s is not valid input.\n", input);
printf("Next month (empty line to quit): ");
}
puts("bye");
return 0;
}
int days(char * m)
{
int total = 0;
int mon_num = 0;
int i;
if (m[0] == '\0')
total = -1;
else
{
m[0] = toupper(m[0]);
for (i = 1; m[i] != '\0'; i++)
m[i] = tolower(m[i]);
for (i = 0; i < 12; i++)
if (strcmp(m, months[i].name) == 0)
{
mon_num = months[i].monumb;
break;
}
if (mon_num == 0)
total = -1;
else
for (i = 0; i < mon_num; i++)
total +=months[i].days;
}
return total;
}
#include
#include
#define MAXTITL 40
#define MAXAUTL 40
#define MAXBKS 100
struct book {
char title[MAXTITL];
char author[MAXAUTL];
float value;
};
void sortt(struct book * pb[], int n);
void sortv(struct book * pb[], int n);
int main(void)
{
struct book library[MAXBKS];
struct book * pbk[MAXBKS];
int count = 0;
int index;
printf("Please enter the book title.\n");
printf("Press [enter] at the start of a line to stop.\n");
while (count < MAXBKS && gets(library[count].title) != NULL
&& library[count].title[0] != '\0')
{
printf("Now enter the author.\n");
gets(library[count].author);
printf("Now enter the value.\n");
scanf("%f", &library[count].value);
pbk[count] = &library[count];
count++;
while (getchar() != '\n')
continue;
if (count < MAXBKS)
printf("Enter the next title.\n");
}
printf("Here is the list of your books:\n");
for (index = 0; index < count; index++)
printf("%s by %s: $%.2f\n", library[index].title,
library[index].author, library[index].value);
printf("Here is the list of your books sorted by title:\n");
sortt(pbk, count);
for (index = 0; index < count; index++)
printf("%s by %s: $%.2f\n", pbk[index]->title,
pbk[index]->author, pbk[index]->value);
sortv(pbk, count);
printf("Here is the list of your books sorted by value:\n");
for (index = 0; index < count; index++)
printf("%s by %s: $%.2f\n", pbk[index]->title,
pbk[index]->author, pbk[index]->value);
return 0;
}
void sortt(struct book * pb[], int n)
{
int top, search;
struct book * temp;
for (top = 0; top < n -1; top++)
for (search = top + 1; search < n; search++)
if (strcmp(pb[search]->title, pb[top]->title) < 0)
{
temp = pb[search];
pb[search] = pb[top];
pb[top] = temp;
}
}
void sortv(struct book * pb[], int n)
{
int top, search;
struct book * temp;
for (top = 0; top < n -1; top++)
for (search = top + 1; search < n; search++)
if (pb[search]->value < pb[top]->value)
{
temp = pb[search];
pb[search] = pb[top];
pb[top] = temp;
}
}
#include
#include
#define LEN 14
#define CSIZE 4
#define SCORES 3
struct name {
char first[LEN];
char last[LEN];
};
struct student {
struct name person;
float scores[SCORES];
float mean;
};
void get_scores(struct student ar[], int lim);
void find_means(struct student ar[], int lim);
void show_class(const struct student ar[], int lim);
void show_ave(const struct student ar[], int lim);
int main(void)
{
struct student class[CSIZE] ={
{ "Flip", "Snide"},
{ "Clare", "Voyans"},
{ "Bingo", "Higgs"},
{ "Fawn", "Hunter"}
};
get_scores(class, CSIZE);
find_means(class, CSIZE);
show_class(class, CSIZE);
show_ave(class, CSIZE);
return 0;
}
void get_scores(struct student ar[], int lim)
{
int i,j;
for (i = 0; i < lim; i++)
{
printf ("Please enter %d scores for %s %s:\n", SCORES,
ar[i].person.first, ar[i].person.last);
for (j = 0; j < SCORES; j++)
{
while (scanf("%f", &ar[i].scores[j]) != 1)
{
scanf("%*s");
puts("Please use numeric input.");
}
}
}
}
void find_means(struct student ar[], int lim)
{
int i, j;
float sum;
for (i = 0; i < lim; i++)
{
for (sum = 0, j = 0; j < SCORES; j++)
sum += ar[i].scores[j];
ar[i].mean = sum / SCORES;
}
}
void show_class(const struct student ar[], int lim)
{
int i, j;
char wholename[2*LEN];
for (i = 0; i < lim; i++)
{
strcpy(wholename, ar[i].person.first);
strcat(wholename, " ");
strcat(wholename, ar[i].person.last);
printf("'s: ", wholename);
for (j = 0; j < SCORES; j++)
printf("%6.1f ", ar[i].scores[j]);
printf(" Average = %5.2f\n", ar[i].mean);
}
}
void show_ave (const struct student ar[], int lim)
{
int i, j;
float total;
printf("\n's: ", "QUIZ AVERAGES");
for (j = 0; j < SCORES; j++)
{
for (total = 0, i = 0; i < lim; i++)
total += ar[i].scores[j];
printf("%6.2f ", total / lim);
}
putchar('\n');
}
#include
#include
#include
#define MAXTITL 40
#define MAXAUTL 40
#define MAXBKS 10
#define CONTINUE 0
#define DONE 1
#define YES 1
#define NO 0
struct book {
char title[MAXTITL];
char author[MAXAUTL];
float value;
int delete;
};
int getlet(const char * s);
int getbook(struct book * pb);
void update(struct book * item);
int main(void)
{
struct book library[MAXBKS];
int count = 0;
int deleted = 0;
int index, filecount, open;
FILE * pbooks;
int size = sizeof (struct book);
if ((pbooks = fopen("book.dat", "r")) != NULL)
{
while (count < MAXBKS && fread(&library[count], size,
1, pbooks) == 1)
{
if (count == 0)
puts("Current contents of book.dat:");
printf("%s by %s: $%.2f\n",library[count].title,
library[count].author, library[count].value);
printf("Do you wish to change or delete this entry?
if (getlet("yn") == 'y')
{
printf("Enter c to change, d to delete entry: ");
if (getlet("cd") == 'd')
{
library[count].delete = YES;
deleted++;
puts("Entry marked for deletion.");
}
else
update(&library[count]);
}
count++;
}
fclose(pbooks);
}
filecount = count - deleted;
if (count == MAXBKS)
{
fputs("The book.dat file is full.", stderr);
exit(2);
}
puts("Please add new book titles.");
puts("Press [enter] at the start of a line to stop.");
open = 0;
while (filecount < MAXBKS)
{
if (filecount < count)
{
while (library[open].delete == NO)
open++;
if (getbook(&library[open]) == DONE)
break;
}
else if (getbook(&library[filecount]) == DONE)
break;
filecount++;
if (filecount < MAXBKS)
puts("Enter the next book title.");
}
puts("Here is the list of your books:");
for (index = 0; index < filecount; index++)
if (library[index].delete == NO)
printf("%s by %s: $%.2f\n",library[index].title,
library[index].author, library[index].value);
if ((pbooks = fopen("book.dat", "w")) == NULL)
{
fputs("Can't open book.dat file for output\n",stderr);
exit(1);
}
for (index = 0; index < filecount; index++)
if (library[index].delete == NO)
fwrite(&library[index], size, 1, pbooks);
fclose(pbooks);
puts("Done!");
return 0;
}
int getlet(const char * s)
{
char c;
c = getchar();
while (strchr(s, c) == NULL)
{
printf ("Enter a character in the list %s\n", s);
while( getchar() != '\n')
continue;
c = getchar();
}
while (getchar() != '\n')
continue;
return c;
}
int getbook(struct book * pb)
{
int status = CONTINUE;
if (gets(pb->title) == NULL || pb->title[0] == '\0')
status = DONE;
else
{
printf ("Now enter the author: ");
gets (pb->author);
printf ("Now enter the value: ");
while (scanf("%f", &pb->value ) != 1)
{
puts("Please use numeric input");
scanf("%*s");
}
while (getchar() != '\n')
continue;
pb->delete = NO;
}
return status;
}
void update(struct book * item)
{
struct book copy;
char c;
copy = *item;
puts("Enter the letter that indicates your choice:");
puts("t) modify title a) modify author");
puts("v) modify value s) quit, saving changes");
puts("q) quit, ignore changes");
while ( (c = getlet("tavsq")) != 's' && c != 'q')
{
switch ( c )
{
case 't' : puts("Enter new title: ");
gets (copy.title);
break;
case 'a' : puts("Enter new author: ");
gets (copy.author);
break;
case 'v' : puts("Enter new value: ");
while (scanf("%f", ©.value) != 1)
{
puts ("Enter a numeric value: ");
scanf("%*s");
}
while( getchar() != '\n')
continue;
break;
}
puts("t) modify title a) modify author");
puts("v) modify value s) quit, saving changes");
puts("q) quit, ignore changes");
}
if (c == 's')
*item = copy;
}
#include
#include
#include
#include
#define LEN 14
#define SEATS 12
#define EMPTY 0
#define TAKEN 1
#define CONTINUE 1
#define DONE 0
struct planestats {
int seat_id;
int status;
char last[LEN];
char first[LEN];
};
int getmenu(void);
int getlet(const char *);
int openings(const struct planestats [], int);
void show_empties(const struct planestats [], int);
void list_assign(struct planestats *[], int);
void assign_seat(struct planestats [], int);
void delete_seat(struct planestats [], int);
void show_seats(const struct planestats [], int);
void sort(struct planestats *[], int);
void makelist(const struct planestats [], char *, int);
int main(void)
{
struct planestats plane_1[SEATS], *ps[SEATS];
int choice;
int i;
FILE *fp;
size_t size = sizeof(struct planestats);
for ( i = 0; i < SEATS; i++)
ps[i] = &plane_1[i];
if ((fp = fopen("air.dat", "rb")) == NULL )
for (i = 0; i < SEATS; i++)
{
plane_1[i].status = EMPTY;
plane_1[i].seat_id = i + 1;
}
else
{
fread(plane_1, size, SEATS, fp);
fclose(fp);
}
while ( (choice = getmenu() ) != 'q')
{
switch (choice)
{
case 'o' : printf ("There are %d empty seats.\n",
penings(plane_1, SEATS));
break;
case 'e' : show_empties(plane_1, SEATS);
break;
case 'l' : list_assign(ps, SEATS);
break;
case 'a' : assign_seat(plane_1, SEATS);
break;
case 'd' : delete_seat(plane_1, SEATS);
break;
default : puts("Switch trouble");
break;
}
}
if((fp = fopen("air.dat", "wb")) == NULL )
puts("Can't save data to file.");
else
{
fwrite(plane_1, size, SEATS, fp);
fclose(fp);
}
puts("Bye from Colossus Airlines!");
return 0;
}
#define CHOICES 6
int getmenu(void)
{
const char *descript[CHOICES] = {
"Show number of empty seats",
"Show list of empty seats",
"Show alphabetical list of seat assignments",
"Assign a customer to a seat",
"Delete a seat assignment",
"Quit"
};
const char labels[CHOICES + 1] = "oeladq";
int i;
puts("To choose a function, enter its letter label");
for (i = 0; i < CHOICES; i++)
printf("%c) %s\n", labels[i], descript[i]);
return getlet(labels);
}
int getlet(const char * s)
{
char c;
c = getchar();
while (strchr(s, c) == NULL)
{
printf ("Enter a character in the list %s\n", s);
while( getchar() != '\n')
continue;
c = getchar();
}
while (getchar() != '\n')
continue;
return c;
}
int openings(const struct planestats pl[], int n)
{
int count = 0;
int seat;
for (seat = 0; seat < n; seat++)
if (pl[seat].status == EMPTY)
count++;
return count;
}
void show_empties(const struct planestats pl[], int n)
{
int seat;
char seating[3* SEATS];
if ( openings(pl,n) == 0)
puts("All seats are assigned");
else
{
puts("The following seats are available:");
makelist(pl, seating, EMPTY);
puts (seating) ;
}
}
void makelist(const struct planestats pl[], char * str, int kind)
{
int seat;
char temp[LEN];
str[0] = '\0';
for (seat = 0; seat < SEATS; seat++)
if (pl[seat].status == kind)
{
sprintf(temp," %d", pl[seat].seat_id);
strcat(str, temp);
}
}
void list_assign(struct planestats *ps[], int n)
{
int i;
if (openings(*ps, n) == SEATS)
puts("All seats are empty.");
else
{
sort(ps, n);
for(i = 0; i < SEATS; i++)
if ( ps[i]->status == TAKEN )
printf ("Seat %d: %s, %s\n",
ps[i]->seat_id, ps[i]->last, ps[i]->first);
}
}
void assign_seat(struct planestats pl[], int n)
{
char list[3 * SEATS];
int seat, loop;
if (openings(pl,n) == 0)
puts("All seats are assigned.");
else
{
makelist(pl,list, EMPTY);
puts("Which seat do you want? Choose from this list:");
puts (list) ;
do
{
while( scanf("%d", &seat) != 1)
{
scanf("%*s");
puts("Enter a number from this list:");
puts (list) ;
}
if (seat < 1 || seat > SEATS ||
pl[seat-1].status == TAKEN)
{
puts("Enter a number from this list:");
puts (list) ;
loop = CONTINUE;
}
else
loop = DONE;
} while (loop == CONTINUE);
while (getchar() != '\n')
continue;
puts("Enter first name:");
gets (pl[seat - 1].first);
puts("Enter last name:");
gets (pl[seat - 1].last);
printf("%s %s assigned to seat %d.\n",
pl[seat - 1].first, pl[seat - 1].last, seat);
puts("Enter a to accept assignment, c to cancel it.");
if (getlet("ac") == 'a')
{
pl[seat - 1].status = TAKEN;
puts("Passenger assigned to seat.");
}
else
puts("Passenger not assigned.");
}
}
void delete_seat(struct planestats pl[], int n)
{
int seat, loop;
char list[3 * SEATS];
if (openings(pl, n) == SEATS)
puts("All seats already are empty.");
else
{
show_seats(pl, n);
makelist(pl, list, TAKEN);
puts("Enter the number of the seat to be cancelled:");
do
{
while( scanf("%d", &seat) != 1)
{
scanf("%*s");
puts("Enter a number from this list:");
puts (list) ;
}
if (seat < 1 || seat > SEATS ||
pl[seat-1].status == EMPTY)
{
puts("Enter a number from this list:");
puts (list) ;
loop = CONTINUE;
}
else
loop = DONE;
} while (loop == CONTINUE);
while (getchar() != '\n')
continue;
printf("%s %s to be canceled for seat %d.\n",
pl[seat - 1].first, pl[seat - 1].last, seat);
puts("Enter d to delete assignment, a to abort.");
if ( getlet("da") == 'd')
{
pl[seat - 1].status = EMPTY;
puts ("Passenger dropped.");
}
else
puts("Passenger retained.");
}
}
void show_seats(const struct planestats pl[], int n)
{
int i;
puts("Seats currently taken:");
for (i = 0; i < SEATS; i++)
if (pl[i].status == TAKEN)
printf("Seat %d: %s, %s\n", pl[i].seat_id,
pl[i].last, pl[i].first);
}
void sort(struct planestats *array[], int limit)
{
int top, search;
struct planestats * temp;
for (top = 0; top < limit -1; top++)
for (search = top + 1; search < limit; search++)
if (strcmp(array[search]->last, array[top]->last) < 0)
{
temp = array[search];
array[search] = array[top];
array[top] = temp;
}
}
#include
#include
double twice(double x);
double half(double x);
double thrice(double x);
void showmenu(void);
#define NUM 4
int main(void)
{
double (*pf[NUM])(double) = {twice, half, thrice, sqrt};
double val;
double ans;
int sel;
printf("Enter a number (negative to quit): ");
while (scanf("%lf", &val) && val >= 0)
{
showmenu();
while (scanf("%d", &sel) && sel >= 0 && sel <= 3)
{
ans = (*pf[sel])(val);
printf("answer = %f\n", ans);
showmenu();
}
printf("Enter next number (negative to quit): ");
}
puts("bye");
return 0;
}
void showmenu(void)
{
puts("Enter one of the following choices:");
puts("0) double the value 1) halve the value");
puts("2) triple the value 3) squareroot the value");
puts("4) next number");
}
double twice(double x) {return 2.0 * x;}
double half(double x) {return x / 2.0;};
double thrice(double x) {return 3.0 * x;}
Chapter 15
#include
#include
int bstr_to_dec(const char * str);
bool check_val(const char * str);
int main(void)
{
char value[8* sizeof (int) + 1];
printf("Enter a binary number with up to %d digits: ", 8 * sizeof(int));
while (gets(value) && value[0] != '\0')
{
if (!check_val(value))
puts("A binary number contains just 0s and 1s.");
else
printf("%s is %d\n", value, bstr_to_dec(value));
puts("Enter next value:");
}
puts("Done");
return 0;
}
int bstr_to_dec(const char * str)
{
int val = 0;
while (*str != '\0')
val = 2 * val + (*str++ - '0');
return val;
}
bool check_val(const char * str)
{
bool valid = true;
while (valid && *str != '\0')
{
if (*str != '0' && *str != '1')
valid = false;
++str;
}
return valid;
}
int bstr_to_dec(const char * str);
char * itobs(int, char *);
int main(int argc, char * argv[])
{
int v1;
int v2;
char bstr[8* sizeof (int) + 1];
if (argc != 3)
{
fprintf(stderr, "Usage: %s binarynum1 binarynum2\n", argv[0]);
exit(EXIT_FAILURE);
}
v1 = bstr_to_dec(argv[1]);
v2 = bstr_to_dec(argv[2]);
printf("~%s = %s\n", argv[1], itobs(~v1, bstr));
printf("~%s = %s\n", argv[2], itobs(~v2, bstr));
printf("%s & %s= %s\n", argv[1], argv[2], itobs(v1 & v2, bstr));
printf("%s | %s= %s\n", argv[1], argv[2], itobs(v1 | v2, bstr));
printf("%s ^ %s= %s\n", argv[1], argv[2], itobs(v1 ^ v2, bstr));
puts("Done");
return 0;
}
int bstr_to_dec(const char * str)
{
int val = 0;
while (*str != '\0')
val = 2 * val + (*str++ - '0');
return val;
}
char * itobs(int n, char * ps)
{
int i;
static int size = 8 * sizeof(int);
for (i = size - 1; i >= 0; i--, n >>= 1)
ps[i] = (01 & n) + '0';
ps[size] = '\0';
return ps;
}
#include
char * itobs(int, char *);
int onbits(int);
int main(int argc, char * argv[])
{
int val;
char bstr[8* sizeof (int) + 1];
printf("Enter an integer (negative to quit): ");
while (scanf("%d", &val) && val >= 0)
{
printf ("%d (%s) has %d bits on.\n", val,
itobs(val, bstr), onbits(val));
printf("Next value: ");
}
puts("Done");
return 0;
}
char * itobs(int n, char * ps)
{
int i;
static int size = 8 * sizeof(int);
for (i = size - 1; i >= 0; i--, n >>= 1)
ps[i] = (01 & n) + '0';
ps[size] = '\0';
return ps;
}
int onbits(int n)
{
static const int size = 8 * sizeof(int);
int ct = 0;
int i;
for (i = 0; i < size; i++, n >>= 1)
if ((1 & n) == 1)
ct++;
return ct;
}
#include
unsigned int rotate_l(unsigned int, unsigned int);
char * itobs(int, char *);
int main(void)
{
unsigned int val;
unsigned int rot;
unsigned int places;
char bstr1[8* sizeof (int) + 1];
char bstr2[8* sizeof (int) + 1];
printf("Enter an integer (0 to quit): ");
while (scanf("%ud", &val) && val > 0)
{
printf("Enter the number of bits to be rotated: \n");
scanf("%ul", &places);
rot = rotate_l(val, places);
itobs(val, bstr1);
itobs(rot, bstr2);
printf ("%u rotated is %u.\n", val, rot );
printf("%s rotated is %s.\n", bstr1, bstr2);
printf("Next value: ");
}
puts("Done");
return 0;
}
unsigned int rotate_l(unsigned int n, unsigned int b)
{
static const int size = 8 * sizeof(int);
unsigned int overflow;
b %= size;
overflow = n >> (size - b);
return (n << b) | overflow;
}
char * itobs(int n, char * ps)
{
int i;
static int size = 8 * sizeof(int);
for (i = size - 1; i >= 0; i--, n >>= 1)
ps[i] = (01 & n) + '0';
ps[size] = '\0';
return ps;
}
#include
#include
#include
#define ID_MASK 0xFF
#define SIZE_MASK 0x7F00
#define LEFT 0x00000
#define CENTER 0x08000
#define RIGHT 0x10000
#define ALIGN_MASK 0x18000
#define REGULAR 0x00000
#define BOLD 0x20000
#define ITALIC 0x40000
#define UNDERLINE 0x80000
#define STYLE_MASK 0xE0000
#define SIZE_SHIFT 8
typedef unsigned long font;
char do_menu(font * f);
char get_choice(const char *);
void show_menu(void);
void show_font(font f);
void eatline(void);
void get_id(font * f);
void get_size(font * f);
void get_align(font * f);
int main(void)
{
font sample = 1 | (12 < while (do_menu(&sample) != 'q') continue; puts("Bye!"); return 0; } char do_menu(font * f) { char response; show_font(*f); show_menu(); response = get_choice("fsabiuq"); switch(response) { case 'f' : get_id(f); break; case 's' : get_size(f); break; case 'a' : get_align(f); break; case 'b' : *f ^= BOLD; break; case 'i' : *f ^= ITALIC; break; case 'u' : *f ^= UNDERLINE; break; case 'q' : break; default : fprintf(stderr, "menu problem\n"); } return response; } char get_choice(const char * str) { char ch; ch = getchar(); ch = tolower(ch); eatline(); while (strchr(str, ch) == NULL) { printf("Please enter one of the following: %s\n", str); ch = tolower(getchar()); eatline(); } return ch; } void eatline(void) { while (getchar() != '\n') continue; } void show_menu(void) { puts("f)change font s)change size a)change alignment"); puts("b)toggle bold i)toggle italic u)toggle underline"); puts("q)quit"); } void show_font(font f) { printf("\n%4s %4s %9s %3s %3s %3s\n", "ID", "SIZE", "ALIGNMENT", "B", "I", "U"); printf("M M", f & ID_MASK, (f & SIZE_MASK) >> SIZE_SHIFT); switch(f & ALIGN_MASK) { case LEFT : printf("%7s", "left"); break; case RIGHT : printf("%7s", "right"); break; case CENTER : printf("%7s", "center"); break; default : printf("%7s", "unknown"); break; } printf("%8s %3s %3s\n\n", (f & BOLD) == BOLD? "on" : "off", (f & ITALIC) == ITALIC ? "on" : "off", (f & UNDERLINE) == UNDERLINE ? "on" : "off"); } void get_id(font * f) { int id; printf("Enter font ID (0-255): "); scanf("%d", &id); id = id & ID_MASK; *f |= id; eatline(); } void get_size(font * f) { int size; printf("Enter font size (0-127): "); scanf("%d", &size); *f |= (size << SIZE_SHIFT) & SIZE_MASK; eatline(); } void get_align(font * f) { puts("Select alignment:"); puts("l)left c)center r)right"); switch (get_choice("lcr")) { case 'l' : *f &= ~ALIGN_MASK; *f |= LEFT; break; case 'c' : *f &= ~ALIGN_MASK; *f |= CENTER; break; case 'r' : *f &= ~ALIGN_MASK; *f |= RIGHT; break; default : fprintf(stderr, "alignment problem\n"); } } Chapter 16 #include #define HMEAN(X,Y) (2.0 * (X) *(Y) / ((X) + (Y))) int main(void) { double x, y, ans; while (scanf("%lf %lf", &x, &y) == 2) { ans = HMEAN(x,y); printf("%g = harmonic mean of %g %g.\n", ans, x, y); ans = HMEAN(x - y, x +y); printf("%g = harmonic mean of %g %g.\n", ans, x - y, x + y); } puts("Bye"); return 0; } #include #include struct polar { double r; double theta; }; struct rect { double x; double y; }; struct rect p_to_r(const struct polar * ppol); int main(void) { struct polar input; struct rect answer; while (scanf("%lf %lf", &input.r, &input.theta) == 2) { answer = p_to_r(&input); printf("polar coord: %g %f\n",input.r, input.theta); printf("rectangular coord: %g %f\n",answer.x, answer.y); } puts("Bye"); return 0; } struct rect p_to_r(const struct polar * ppol) { static const double deg_rad = 3.141592654 / 180.0; struct rect res; double ang = deg_rad * ppol->theta; res.x = ppol->r * sin(ang); res.y = ppol->r * cos(ang); return res; } #include #include void wait(double t); void random_pick(int ar[], int arsize, int picks); #define SPOTS 51 #define PICKS 6 int main() { int lotto[SPOTS]; int i; char ch; for (i = 0; i < SPOTS; i++) lotto[i] = i + 1; do { random_pick(lotto, SPOTS, PICKS); printf ("Again? ch = getchar(); while (getchar() != '\n') continue; } while (ch == 'y' || ch == 'Y'); puts ("Done"); return 0; } void random_pick(int ar[], int arsize, int picks) { int i, index, temp; srand(time(0)); if (picks > arsize) { fputs("Number of picks > array size\n", stderr); fputs("Setting picks = array size\n", stderr); picks = arsize; } for (i = 0; i < picks; i++) { index = rand() % (arsize - 1); temp = ar[index]; printf ("- ", temp); if (i % 20 == 19) putchar('\n'); ar[index] = ar[arsize - 1]; ar[arsize - 1] = temp; arsize--; } if (i % 20 != 0) putchar('\n'); } // pe16-7.c.-- using a variadic function #include #include #include void show_array(const double ar[], int n); double * new_d_array(int n, ...); int main() { double * p1; double * p2; p1 = new_d_array(5, 1.2, 2.3, 3.4, 4.5, 5.6); p2 = new_d_array(4, 100.0, 20.00, 8.08, -1890.0); show_array(p1, 5); show_array(p2, 4); free(p1); free(p2); return 0; } void show_array(const double ar[], int n) { int i; for (i = 0; i < n; i++) printf("%g ", ar[i]); putchar('\n'); } double * new_d_array(int n, ...) { va_list ap; int i; double * pt; va_start(ap, n); pt = (double *) malloc(n * sizeof(double)); for (i = 0; i< n; i++) pt[i] = va_arg(ap, double); va_end(ap); return pt; } Chapter 17 #include #include #include #define TSIZE 45 struct film { char title[TSIZE]; int rating; struct film * next; }; void show_rec(const struct film * pf); int main(void) { struct film * head = NULL; struct film * prev, * current; char input[TSIZE]; puts("Enter first movie title:"); while (gets(input) != NULL && input[0] != '\0') { current = (struct film *) malloc(sizeof(struct film)); if (head == NULL) head = current; else prev->next = current; current->next = NULL; strcpy(current->title, input); puts("Enter your rating <0-10>:"); scanf("%d", ¤t->rating); while(getchar() != '\n') continue; puts("Enter next movie title (empty line to stop):"); prev = current; } if (head == NULL) printf("No data entered. "); else printf ("Here is the movie list:\n"); current = head; while (current != NULL) { printf("Movie: %s Rating: %d\n", current->title, current->rating); current = current->next; } if (head != NULL) { printf("\nHere is the list in reverse order:\n"); show_rec(head); } printf("Bye!\n"); return 0; } void show_rec(const struct film * pf) { if (pf->next != NULL) show_rec(pf->next); printf("Movie: %s Rating: %d\n", pf->title, pf->rating); } #include #include #include #define TSIZE 45 struct film { char title[TSIZE]; int rating; struct film * next; struct film * prev; }; int main(void) { struct film * head = NULL; struct film * prev, * current; char input[TSIZE]; puts("Enter first movie title:"); while (gets(input) != NULL && input[0] != '\0') { current = (struct film *) malloc(sizeof(struct film)); if (head == NULL) { head = current; head->prev = NULL; } else { prev->next = current; current->prev = prev; } current->next = NULL; strcpy(current->title, input); puts("Enter your rating <0-10>:"); scanf("%d", ¤t->rating); while(getchar() != '\n') continue; puts("Enter next movie title (empty line to stop):"); prev = current; } if (head == NULL) printf("No data entered. "); else printf ("Here is the movie list:\n"); current = head; while (current != NULL) { printf("Movie: %s Rating: %d\n", current->title, current->rating); prev = current; current = current->next; } if (head != NULL) { printf("\nHere is the list in reverse order:\n"); current = prev; while (current != NULL) { printf("Movie: %s Rating: %d\n", current->title, current->rating); current = current->prev; } } printf("Bye!\n"); return 0; } #ifndef LIST_H_ #define LIST_H_ #include #define TSIZE 45 struct film { char title[TSIZE]; int rating; }; typedef struct film Item; typedef struct node { Item item; struct node * next; } Node; #define MAXSIZE 100 typedef struct list { Item entries[MAXSIZE]; int items; } List; void InitializeList(List * plist); bool ListIsEmpty(const List * plist); bool ListIsFull(const List * plist); unsigned int ListItemCount(const List * plist); bool AddItem(Item item, List * plist); void Traverse (const List * plist, void (* pfun)(Item item) ); void EmptyTheList(List * plist); #endif #include #include #include "list17-3.h" void showmovies(Item item); int main(void) { List movies; Item temp; InitializeList(&movies); if (ListIsFull(&movies)) { fprintf(stderr,"No memory available! Bye!\n"); exit(1); } puts("Enter first movie title:"); while (gets(temp.title) != NULL && temp.title[0] != '\0') { puts("Enter your rating <0-10>:"); scanf("%d", &temp.rating); while(getchar() != '\n') continue; if (AddItem(temp, &movies)==false) { fprintf(stderr,"Problem allocating memory\n"); break; } if (ListIsFull(&movies)) { puts("The list is now full."); break; } puts("Enter next movie title (empty line to stop):"); } if (ListIsEmpty(&movies)) printf("No data entered. "); else { printf ("Here is the movie list:\n"); Traverse(&movies, showmovies); } printf("You entered %d movies.\n", ListItemCount(&movies)); EmptyTheList(&movies); printf("Bye!\n"); return 0; } void showmovies(Item item) { printf("Movie: %s Rating: %d\n", item.title, item.rating); } #include #include #include "list17-3.h" void InitializeList(List * plist) { plist->items = 0; } bool ListIsEmpty(const List * plist) { if (plist->items == 0) return true; else return false; } bool ListIsFull(const List * plist) { if (plist->items == MAXSIZE) return true; else return false; } unsigned int ListItemCount(const List * plist) { return plist->items; } bool AddItem(Item item, List * plist) { if (plist->items == MAXSIZE) return false; else { plist->entries[plist->items++] = item; return true; } } void Traverse (const List * plist, void (* pfun)(Item item) ) { int i; for (i = 0; i < plist->items; i++) (*pfun)(plist->entries[i]); } void EmptyTheList(List * plist) { plist->items = 0; } #ifndef STACK_H_ #define STACK_H_ #include typedef char Item; #define MAXSTACK 100 typedef struct stack { Item items[MAXSTACK]; int top; } Stack; void InitializeStack(Stack * ps); bool FullStack(const Stack * ps); bool EmptyStack(const Stack *ps); bool Push(Item item, Stack * ps); bool Pop(Item *pitem, Stack * ps); #endif #include #include "pe17-5.h" #define SLEN 81 int main(void) { Stack stch; char temp[SLEN]; int i; char ch; InitializeStack(&stch); printf("Enter a line (an empty line to quit): \n"); while (gets(temp) && temp[0] != '\0') { i = 0; while (temp[i] != '\0' && !FullStack(&stch)) Push(temp[i++], &stch); while (!EmptyStack(&stch)) { Pop(&ch, &stch); putchar(ch); } putchar('\n'); printf("Enter next line (empty line to quit): "); } puts("Done!"); return 0; } #include #include #include "pe17-5.h" void InitializeStack(Stack * ps) { ps->top = 0; } bool FullStack(const Stack * ps) { return ps->top == MAXSTACK; } bool EmptyStack(const Stack *ps) { return ps->top == 0; } bool Push(Item item, Stack * ps) { if (ps->top == MAXSTACK) return false; else { ps->items[ps->top++] = item; return true; } } bool Pop(Item *pitem, Stack * ps) { if (ps->top == 0) return false; else { ps->top--; *pitem = ps->items[ps->top]; return true; } } #ifndef _TREE_H_ #define _TREE_H_ #include #define SLEN 81 typedef struct item { char wrd[SLEN]; int count; } Item; #define MAXITEMS 100 typedef struct node { Item item; struct node * left; struct node * right; } Node; typedef struct tree { Node * root; int size; } Tree; void InitializeTree(Tree * ptree); bool TreeIsEmpty(const Tree * ptree); bool TreeIsFull(const Tree * ptree); int TreeItemCount(const Tree * ptree); bool AddItem(const Item * pi, Tree * ptree); bool InTree(const Item * pi, const Tree * ptree); bool DeleteItem(const Item * pi, Tree * ptree); void Traverse (const Tree * ptree, void (* pfun)(Item item)); void DeleteAll(Tree * ptree); const Item * WhereInTree(const Item * pi, const Tree * ptree); #endif #include #include #include #include #include "pe17-7.h" void printitem(Item item); char menu(void); void showwords (const Tree * pt); void findword (const Tree * pt); #define SLEN 81 int main(void) { Tree wordcount; FILE * fp; char filename[SLEN]; char word[SLEN]; Item entry; char choice; printf ("Enter name of file to be processed: \n"); gets(filename); if ((fp = fopen(filename, "r")) == 0) { printf("Can't open file %s. Bye.\n", filename); exit(EXIT_FAILURE); } InitializeTree(&wordcount); while (fscanf(fp, "%s", word) == 1 && !TreeIsFull(&wordcount)) { strcpy(entry.wrd, word); AddItem(&entry, &wordcount); } while ((choice = menu()) != 'q') { switch (choice) { case 's' : showwords(&wordcount); break; case 'f' : findword(&wordcount); break; default : puts("Switching error"); } } fclose(fp); puts("Done"); return 0; } char menu(void) { int ch; puts("Word counting program"); puts("Enter the letter corresponding to your choice:"); puts("s) show word list f) find a word"); puts("q) quit"); while ((ch = getchar()) != EOF) { while (getchar() != '\n') continue; ch = tolower(ch); if (strchr("sfq",ch) == NULL) puts("Please enter an s, f, or q:"); else break; } if (ch == EOF) ch = 'q'; return ch; } void showwords (const Tree * pt) { if (TreeIsEmpty(pt)) puts("No entries!"); else Traverse(pt, printitem); } void findword (const Tree * pt) { char word[SLEN]; Item entry; const Item * pi; if (TreeIsEmpty(pt)) { puts("No entries!"); return; } printf("Enter the word to find: "); scanf("%s", word); while (getchar() != '\n') continue; strcpy(entry.wrd, word); pi = WhereInTree(&entry, pt); if (pi == NULL) printf("%s is not in the list.\n", word); else printf("%s appears %d times.\n", word, pi->count); } void printitem(Item item) { printf("=: %s\n", item.count, item.wrd); } #include #include #include #include "pe17-7.h" typedef struct pair { Node * parent; Node * child; } Pair; static Node * MakeNode(const Item * pi); static bool ToLeft(const Item * i1, const Item * i2); static bool ToRight(const Item * i1, const Item * i2); static void AddNode (Node * new_node, Node * root); static void InOrder(const Node * root, void (* pfun)(Item item)); static Pair SeekItem(const Item * pi, const Tree * ptree); static void DeleteNode(Node **ptr); static void DeleteAllNodes(Node * ptr); void InitializeTree(Tree * ptree) { ptree->root = NULL; ptree->size = 0; } bool TreeIsEmpty(const Tree * ptree) { if (ptree->root == NULL) return true; else return false; } bool TreeIsFull(const Tree * ptree) { if (ptree->size == MAXITEMS) return true; else return false; } int TreeItemCount(const Tree * ptree) { return ptree->size; } bool AddItem(const Item * pi, Tree * ptree) { Node * new; Pair seek; if (TreeIsFull(ptree)) { fprintf(stderr,"Tree is full\n"); return false; } if ((seek = SeekItem(pi, ptree)).child != NULL) { seek.child->item.count++; return true; } new = MakeNode(pi); if (new == NULL) { fprintf(stderr, "Couldn't create node\n"); return false; } ptree->size++; if (ptree->root == NULL) ptree->root = new; else AddNode(new,ptree->root); return true; } bool InTree(const Item * pi, const Tree * ptree) { return (SeekItem(pi, ptree).child == NULL) ? false : true; } const Item * WhereInTree(const Item * pi, const Tree * ptree) { Node * pn; pn = SeekItem(pi,ptree).child; if (pn != NULL) return &(pn->item); else return NULL; } bool DeleteItem(const Item * pi, Tree * ptree) { Pair look; look = SeekItem(pi, ptree); if (look.child == NULL) return false; if (look.child->item.count > 0) look.child->item.count--; else { if (look.parent == NULL) DeleteNode(&ptree->root); else if (look.parent->left == look.child) DeleteNode(&look.parent->left); else DeleteNode(&look.parent->right); ptree->size--; } return true; } void Traverse (const Tree * ptree, void (* pfun)(Item item)) { if (ptree != NULL) InOrder(ptree->root, pfun); } void DeleteAll(Tree * ptree) { if (ptree != NULL) DeleteAllNodes(ptree->root); ptree->root = NULL; ptree->size = 0; } static void InOrder(const Node * root, void (* pfun)(Item item)) { if (root != NULL) { InOrder(root->left, pfun); (*pfun)(root->item); InOrder(root->right, pfun); } } static void DeleteAllNodes(Node * root) { Node * pright; if (root != NULL) { pright = root->right; DeleteAllNodes(root->left); free(root); DeleteAllNodes(pright); } } static void AddNode (Node * new_node, Node * root) { if (ToLeft(&new_node->item, &root->item)) { if (root->left == NULL) root->left = new_node; else AddNode(new_node, root->left); } else if (ToRight(&new_node->item, &root->item)) { if (root->right == NULL) root->right = new_node; else AddNode(new_node, root->right); } else { fprintf(stderr,"location error in AddNode()\n"); exit(1); } } static bool ToLeft(const Item * i1, const Item * i2) { if (strcmp(i1->wrd, i2->wrd) < 0) return true; else return false; } static bool ToRight(const Item * i1, const Item * i2) { if (strcmp(i1->wrd, i2->wrd) > 0) return true; else return false; } static Node * MakeNode(const Item * pi) { Node * new_node; new_node = (Node *) malloc(sizeof(Node)); if (new_node != NULL) { new_node->item = *pi; new_node->item.count = 1; new_node->left = NULL; new_node->right = NULL; } return new_node; } static Pair SeekItem(const Item * pi, const Tree * ptree) { Pair look; look.parent = NULL; look.child = ptree->root; if (look.child == NULL) return look; while (look.child != NULL) { if (ToLeft(pi, &(look.child->item))) { look.parent = look.child; look.child = look.child->left; } else if (ToRight(pi, &(look.child->item))) { look.parent = look.child; look.child = look.child->right; } else break; } return look; } static void DeleteNode(Node **ptr) { Node * temp; if ( (*ptr)->left == NULL) { temp = *ptr; *ptr = (*ptr)->right; free(temp); } else if ( (*ptr)->right == NULL) { temp = *ptr; *ptr = (*ptr)->left; free(temp); } else { for (temp = (*ptr)->left; temp->right != NULL; temp = temp->right) continue; temp->right = (*ptr)->right; temp = *ptr; *ptr =(*ptr)->left; free(temp); } }PE 16-2
PE 16-3
PE 16-5
PE 16-7
PE 17-1
PE 17-3
PE 17-5
PE 17-7