If your compiler is running in C99 mode, the specifier you want is "%hhu"
:
if (fscanf(entrada, "%hhu ", &elemento) < 1) {
/* tratar erro de leitura, o arquivo provavelmente está corrompido */
}
The formats of printf()
and scanf()
for numeric values are as follows:
tipo signed unsigned
char %hhd %hhu
short int %hd %hu
int %d %u
long %ld %lu
long long %lld %llu
intmax_t %jd %ju
size_t %zd %zu
ptrdiff_t %td %tu
Alternatively, to aid (?) portability, you can use the macros defined in <inttypes.h>
. These macros expand to string literals that must be concatenated with the rest of your format string, if need be. There are separate macros for printf()
and scanf()
; the types for scanf()
are as per the table below:
tipo signed unsigned
8 bits SCNd8 SCNu8
16 bits SCNd16 SCNu16
32 bits SCNd32 SCNu32
64 bits SCNd64 SCNu64
intmax_t SCNdMAX SCNuMAX
intptr_t SCNdPTR SCNuPTR
Use as:
if (fscanf(entrada, SCNd8, &elemento) < 1) {
/* tratar erro de leitura, o arquivo provavelmente está corrompido */
}
The above reference, which refers to the C language ISO standard, reminds you that the "%i"
specifier is dangerous, since it attempts to guess the prefix base of the number it is reading (in addition to having a natural signal). So if your file has a number written as 011
, it will read 9 instead of 11.