vlad417
vlad417

Reputation: 313

fgets and non-printable characters

Can fgets read non-printable characters into the given char* (it appears I can't)? And if not, what is the alternative that would allow a maximum number of input characters from a stream into a char*?

EDIT (for my particular case)

I have an encoder that prints "Le\D7" to stdout, which is piped to a decoder which grabs that from its stdin using:

if( fgets( inputChars, MAX_BYTES_IN, stdin ) == NULL )
{
    fprintf( stderr, "Trouble getting input\n" );
    return 0;
}

while( inputChars[crntChar] != '\0' && inputChars[crntChar] != '\n' )
{
    printf( "Value %d: %d\n", crntChar, inputChars[crntChar]);
    crntChar++;
}

This results in:

Value 0: 76
Value 1: 101
Value 2: -41

Using fgetc has the same result

Upvotes: 3

Views: 3256

Answers (3)

Dietrich Epp
Dietrich Epp

Reputation: 213338

You're getting a weird value because of the unsigned to signed integer conversion.

char x = 198;

printf("x = %d\n", x);
printf("(unsigned) x = %u\n", (unsigned) x);
printf("(unsigned char) x = %d\n", (unsigned char) x);

Output:

x = -58
(unsigned) x = 4294967238
(unsigned char) x = 198

The (unsigned char) cast is what you want.

Please ignore the signed overflow in my code. Note that if you compile using GCC and the -funsigned-char flag, the output is:

x = 198
(unsigned) x = 198
(unsigned char) x = 198

Upvotes: 1

Oki Sallata
Oki Sallata

Reputation: 374

fgets() will read one line of string, in this case read until new line \n / 0x0A or NULL / EOF.

or maybe you can use unsigned char* for non printable ASCII.

so in my opinion, yes fgets() can read non printable ASCII

Upvotes: 0

Aniket Inge
Aniket Inge

Reputation: 25705

Simplest way is to use fgetc(). fgets() internally relies on fgetc().

But there are many alternatives, fread() being one of them. fscanf().

fgetc() and others read both printable and non-printable characters into a char array. A char is just a 1 byte number encoded in ASCII(or 2 bytes in case of wchar_t). There is no concept of printable and non printable character in C.

Upvotes: 1

Related Questions