#include #include #include "jval.h" #include "stack.h" #include "fields.h" main(int argc, char **argv) { IS is; Stack *s; Jval j; char **lines; int nl, i; /* Get the number of lines */ if (argc != 2) { fprintf(stderr, "usage: stacktail n\n"); exit(1); } nl = atoi(argv[1]); if (nl <= 0) exit(0); /* Intialize stack and input */ s = new_stack(); is = new_inputstruct(NULL); /* Push each line onto the stack */ while (get_line(is) >= 0) { stack_push(s, new_jval_s(strdup(is->text1))); } /* Set nl to be the min of the given nl and the number of lines in standard input. */ if (stack_size(s) < nl) nl = stack_size(s); if (nl == 0) exit(0); /* Allocate an array to hold nl lines, and pop the last nl lines off the stack into that array. We put them into the array in reverse order so that the array is in the right order. */ lines = (char **) malloc(sizeof(char *)*nl); for (i = 0; i < nl; i++) { j = stack_pop(s); lines[nl-i-1] = j.s; } /* Print out the lines by traversing the array forwards */ for (i = 0; i < nl; i++) { printf("%s", lines[i]); } }