2

I'm relatively new to C. I have a binary buffer that I want to print to stdout, like so:

unsigned char buffer[1024];

Is there a way to use printf to output this to stdout? I took a look at the man page for printf, however there is no mention of an unsigned char*, only of const char* for %s.

I suppose I could loop over the buffer and do putchar(buffer[i]), however I think that would be rather inefficient. Is there a way to do this using printf? Should I use something like fwrite instead, would that be more appropriate?

Thanks.

edit: Sorry for the confusion, I'm not looking to convert anything to hexadecimal/binary notation, just write out the buffer as-is. For example, if I had [0x41 0x42 0x42 0x41] in the buffer then I would want to print "ABBA".

7
  • 4
    Yes, fwrite is the way to go. Commented Sep 4, 2016 at 23:44
  • 1
    You could use printf with "%x" to print each character in hexadecimal. Commented Sep 4, 2016 at 23:46
  • printf with a binary string might prove to be a mistake if you use %s, since %s will terminate on the first NUL character, even though NUL is often a valid value in these circumstances. Commented Sep 4, 2016 at 23:48
  • If you just want to write the binary data (i.e., the actual bytes, not some ASCII representation of the values), you can do that with write(1, buffer, sizeof(buffer)) (1 is the file descriptor of stdout). (Don't do that if you're doing other stdio writes to stdout, though.) Commented Sep 4, 2016 at 23:50
  • fwrite is the counterpart to fprintf for raw binary data. They are both C library functions. write OTOH is the low level OS system call that is used to implement fwrite (and fprintf for that matter). fwrite (and fprintf) are buffered, write is not. I am not sure if write is portable, but fwrite is. Commented Sep 5, 2016 at 0:00

1 Answer 1

5

As @redneb said, fwrite should be used for this:

#include <stdio.h>

size_t size = sizeof(buffer); /* or however much you're planning to write */
fwrite(buffer, 1, size, stdout);
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.