From: Thadeu Lima de Souza Cascardo Date: Sun, 28 Jun 2020 01:02:57 +0000 (-0300) Subject: Suporta imprimir atributo como número. X-Git-Url: http://git.cascardo.eti.br/?p=cascardo%2Fdeclara.git;a=commitdiff_plain;h=d5c812c549b81bec3650c72f16d56b8d2302c1bb;hp=6ec61d7d67646324136872daee17d75875b0d39d Suporta imprimir atributo como número. --- diff --git a/lib/attr.c b/lib/attr.c index 3f98dbc..e74ab0a 100644 --- a/lib/attr.c +++ b/lib/attr.c @@ -62,3 +62,29 @@ int attr_out(FILE *f, struct pmhash *attr, char *key, int size) { return fprintf(f, "%-*.*s", size, size, attr_get(attr, key) ?: ""); } + +int attr_out_int(FILE *f, struct pmhash *attr, char *key, int size) +{ + + /* + * As there is no validation of the string when parsed, there is no + * point returning any error when there is a parsing failure here. We + * emit only a warning, then. Unfortunately, there is no line + * information here. + */ + + char *val; + unsigned long long num = 0; + val = attr_get(attr, key); + if (val) { + char *end; + errno = 0; + num = strtoull(val, &end, 0); + if ((end && *end != '\0') || errno) { + fprintf(stderr, "Found invalid value in attribute %s: %s: not a number\n", key, val); + num = 0; + } + } + + return fprintf(f, "%0*llu", size, num); +} diff --git a/lib/attr.h b/lib/attr.h index c0e3bd1..8515f86 100644 --- a/lib/attr.h +++ b/lib/attr.h @@ -26,5 +26,6 @@ int attr_set(struct pmhash **pmhash, char *key, char *val); int attr_parse(struct pmhash **pmhash, char *arg); char * attr_get(struct pmhash *pmhash, char *key); int attr_out(FILE *f, struct pmhash *attr, char *key, int size); +int attr_out_int(FILE *f, struct pmhash *attr, char *key, int size); #endif