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

Asked

Viewed 1,088 times

-1

I am reading an array of a file where each element of this matrix varies from 0 to 255. For this reason I have stored the values within an array of unsigned char type, but am finding some problems with regard 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 conflict of variables' types. Is there any specifier for unsigned char, or some way to make a Typecast within the fcanf function itself, without giving any Warning?

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 numerical 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 assist (?) portability, you can use the macros defined in <inttypes.h>. These macros expand to literals of string which must be concatenated with the rest of your format string if necessary. There are separate macros for printf() and scanf(); the guys for the scanf() are according to 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

It’s used as:

if (fscanf(entrada, SCNd8, &elemento) < 1) {
    /* tratar erro de leitura, o arquivo provavelmente está corrompido */
}

The above reference, which refers to the ISO standard of the C language, recalls that the specifier "%i"is dangerous as it tries to prefix the base of the number you are reading (besides having naturally signal). So if in your file there is a number written as 011, he will read 9 instead of 11.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.