diff --git a/homework07/tailit.c b/homework07/tailit.c index 59cc4de..1b1025b 100644 --- a/homework07/tailit.c +++ b/homework07/tailit.c @@ -16,18 +16,56 @@ void usage(int status) { } List *tail_stream(FILE *stream, size_t limit) { - // TODO - return NULL; + List *sequence = list_create(); + char buffer[BUFSIZ]; + + while (fgets(buffer, sizeof(buffer), stream) != NULL) { + char *line = strdup(buffer); + list_append(sequence, (Value){.string = line}); + + // If over limit, remove the oldest line (head) + if (sequence->size > limit) { + Value old = list_pop(sequence, 0); + free(old.string); // Free the popped line's string + } + } + + return sequence; } /* Main Execution */ int main(int argc, char *argv[]) { + size_t limit = 10; // Set baseline limit + // TODO: Parse command line arguments + if (argc == 2) { + if (strcmp(argv[1], "-h") == 0) { + usage(EXIT_SUCCESS); + } else { + usage(EXIT_FAILURE); + } + } else if (argc == 3) { + if (strcmp(argv[1], "-n") == 0) { + limit = (size_t)atoi(argv[2]); + } else { + usage(EXIT_FAILURE); + } + } else if (argc > 3) { + usage(EXIT_FAILURE); + } // TODO: Construct tail of stream + List *lines = tail_stream(stdin, limit); // TODO: Print out tail + while (lines->size > 0) { + Value v = list_pop(lines, 0); + printf("%s", v.string); + free(v.string); + } + + list_delete(lines, false); return EXIT_SUCCESS; }