diff options
| author | Ben Winston | 2024-05-11 16:08:52 -0400 |
|---|---|---|
| committer | Ben Winston | 2024-05-11 16:08:52 -0400 |
| commit | f961562be296bb1628d27eb18e2b6f01174b8bf4 (patch) | |
| tree | a4c695e83473f0117de1d0db600077f05a7e9321 | |
| parent | fa82dab8db28b3d479698a49bea037f3bf31f82b (diff) | |
add parsing for ints, do pages and published
| -rw-r--r-- | booki.c | 34 |
1 files changed, 31 insertions, 3 deletions
@@ -60,6 +60,22 @@ const char* get_last_word(const char* str) { return 0; } +long parse_int(char* current_pos, char** new_pos) { + char c; + char* value; + + // strtol can handle leading spaces + // will put the first non-digit into endptr + char* endptr; + long ret = strtol(current_pos, &endptr, 10); + bool valid = *endptr == ' ' || *endptr == '\n'; + + *new_pos = endptr; + + if (valid) return ret; + else return 0; +} + struct es parse_string(char* current_pos, char** new_pos) { // TODO handle failure @@ -103,6 +119,9 @@ struct Book parse_book(char* current_pos) { current_pos++; } + // go past the equals sign + current_pos++; + // attr should be the name of the attribute, with (possibly) trailing spaces if (strncmp(attr, "title", 5) == 0) { struct es title = parse_string(current_pos, &new_pos); @@ -124,6 +143,14 @@ struct Book parse_book(char* current_pos) { struct es translator = parse_string(current_pos, &new_pos); book.translator = translator; current_pos = new_pos; + } else if (strncmp(attr, "pages", 5) == 0) { + int pages = parse_int(current_pos, &new_pos); + book.pages = pages; + current_pos = new_pos; + } else if (strncmp(attr, "published", 9) == 0) { + int published = parse_int(current_pos, &new_pos); + book.published = published; + current_pos = new_pos; } // go to (and then past) the newline @@ -276,15 +303,16 @@ void print_book(struct Book book, bool all_fields) { char* intfmt = " - %s: %d\n"; if (book.isbn.ptr) printf(esfmt, "isbn", book.isbn.len, book.isbn.ptr); - if (book.pages != 0) - printf(intfmt, "pages", book.pages); if (book.published) printf(esfmt, "published", book.published); if (book.language.ptr) printf(esfmt, "language", book.language.len, book.language.ptr); if (book.translator.ptr) printf(esfmt, "translator", book.translator.len, book.translator.ptr); - + if (book.pages) + printf(intfmt, "pages", book.pages); + if (book.published) + printf(intfmt, "published", book.published); } } |
