0

Writing code with Winsock.
I currently have this:

fwrite(buff, 1, len, stdout);

How to do it like:

for ( int i = 0; i < len; i++ ) {
printf( "%02x ", unsigned char (buff[i]) );
}
printf( "\n" );

Or should I just remove the fwrite and use the print instead?
I wanted to write it to stdout, cuz I have my option to either write to stdout of write to file.

zikdaljin
  • 95
  • 2
  • 5
  • 14

1 Answers1

2

fprintf (see the docs) is like printf but to an arbitrary file:

fprintf(stdout, "%02x ", unsigned char (buff[i]));
RichieHindle
  • 272,464
  • 47
  • 358
  • 399
  • 1
    An `unsigned char` will be promoted to `int` automatically because it is in the variable argument part of the argument list to `fprintf()` and default promotions apply to those. The cast to `unsigned char` may do some good, too; if the `char` type is signed, the cast prevents sign-extension of characters with the high bit set (0x80..0xFF). (And, strictly strictly, `%x` expects an `unsigned int` — it will treat what is passed as if it were an `unsigned int`, anyway.) – Jonathan Leffler Apr 21 '13 at 21:05
  • @JonathanLeffler: Thanks! - I didn't know that. Answer amended. – RichieHindle Apr 21 '13 at 21:06
  • I see that; I'll leave my first comment as it may help others; I'll delete this one shortly, and it is up to you whether you delete your comment. – Jonathan Leffler Apr 21 '13 at 21:07