diff options
Diffstat (limited to '')
-rw-r--r-- | src/commands/tac.c | 40 |
1 files changed, 26 insertions, 14 deletions
diff --git a/src/commands/tac.c b/src/commands/tac.c index fbd0f74..d188de9 100644 --- a/src/commands/tac.c +++ b/src/commands/tac.c @@ -10,29 +10,36 @@ static void help(void) { } static void print_range(FILE* file, int start, int end) { - int len = end - start; + int len, i; + + len = end - start; fseek(file, start, SEEK_SET); - for (int i = 0; i < len; i++) { + + for (i = 0; i < len; i++) { putchar(getc(file)); } + fflush(stdout); } static char stdin_path[PATH_MAX]; -static FILE* read_stdin() { +static FILE* read_stdin (void) { static bool read; static FILE* file; + int r; + char c; if (read) goto finished; read = true; srand(time(NULL)); - int r = rand() % 1000000; + + r = rand() % 1000000; + sprintf(stdin_path, "/tmp/%d.tac", r); file = get_file(stdin_path, "w"); - char c; while((c = getchar()) != EOF) putc(c, file); fclose(file); @@ -43,15 +50,15 @@ finished: } static void parse_file(FILE* file, struct Stack* stack) { - char buf[1024]; - int read; + char buf[1024], c; + int read, i; int total = 1; stack_push_int(stack, 0); rewind(file); while ((read = fread(buf, 1, 1024, file)) > 0) { - for (int i = 0; i < read; i++) { - char c = buf[i]; + for (i = 0; i < read; i++) { + c = buf[i]; if (c != '\n') continue; stack_push_int(stack, total + i); } @@ -61,34 +68,39 @@ static void parse_file(FILE* file, struct Stack* stack) { static void tac_file(FILE* file) { struct Stack stack; + int last, current; + stack_init(&stack, 80); - parse_file(file, &stack); - rewind(file); - int last, current; + if (!stack_pop_int(&stack, &last)) goto cleanup; + while(stack_pop_int(&stack, ¤t)) { print_range(file, current, last); last = current; } cleanup: + stack_free(&stack); } COMMAND(tac) { + FILE* in; + int i; + parse_help(argc, argv, help); - FILE* in = read_stdin(); + in = read_stdin(); if (argc < 1) { tac_file(in); return EXIT_SUCCESS; } - for (int i = 0; i < argc; i++) { + for (i = 0; i < argc; i++) { FILE* file = get_file(argv[i], "r"); if (file == stdin) { tac_file(in); |