How to read a variable of type unsigned char by the function fscanf?

-1

I am reading an array from a file where each element of this array ranges from 0 to 255. For this reason I have stored the values inside an array of type unsigned char, but I am encountering some problems with respect to which specifier to use. When I use the% i specifier and store it in an unsigned char variable, warnings appear at compile time, indicating type conflict of variables. Is there any specifier for the unsigned char, or some way to do a typecast within the fcanf function itself, without giving any warning?

    
asked by anonymous 18.04.2017 / 15:44

1 answer

0

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.

    
18.04.2017 / 22:23