Q:

C++ output readable hex code from serial port

I got a little bit of C code here that reads output from a serial device.. I am currently using perl to read the data from the device and that works okay, but I would prefer to write something in C to do the same job. 
This is the code I got so far;
#include<stdio.h>   /* Standard input/output definitions */
#include<stdlib.h>
#include<string.h>  /* String function definitions */
#include<unistd.h>  /* UNIX standard function definitions */
#include<fcntl.h>   /* File control definitions */
#include<errno.h>   /* Error number definitions */
#include<termios.h> /* POSIX terminal control definitions */
#include<string.h>
#include<unistd.h>

char *buf;
int fd; /* File descriptor for the port */
int i,n;

int open_port(void)
{
    fd = open("/dev/ttyUSB1", O_RDWR | O_NOCTTY | O_NDELAY);

if (fd == -1)     {
    perror("cannot open");
}
else
    fcntl(fd, F_SETFL, 0);
struct termios options;
tcgetattr(fd, &options);
cfsetispeed(&options, B38400);
cfsetospeed(&options, B38400);
options.c_cflag |= (CLOCAL | CREAD);
tcsetattr(fd, TCSANOW, &options);
options.c_cflag &= ~CSIZE;
options.c_cflag &= ~PARENB;
options.c_cflag &= ~CSTOPB;
options.c_cflag &= ~CSIZE;
options.c_cflag |= CS8;
//    options.c_cflag |= (IXON | IXOFF | IXANY); // xon & xoff on
return (fd);
}

int main(int argc) {
    buf=malloc(4095);
    open_port();
    free(buf);
    while(1){
        read(fd,buf,128);
         printf("%s\n",buf);
    }
    close(fd);
}

When I compile and run it outputs data, but the data I see is in garbage format... what I would like to see is readable hex data like 0AEA4E2A ... anyone has any idea how I can easily transform the data into readable hex code? I have been googling for a while but nothing really seems to do the job. 
This is what I did in perl;
while ($timeout>0) {
        my ($count,$saw)=$PortObj->read(1); # will read _up to_ 255 chars
        if ($count > 0) {
                $chars+=$count;
                $buffer.=$saw; my $hex = unpack 'H*', $saw; printf ($hex);

A:

Presumably you want "unified" hex code, padded with zeroes if necessary, and you also want to print all the data (the "%s" format specifier expects a NUL-terminated string, so if you have zeroes in your binary data, that won't work for sure):
read(fd, buf, 128);
int i;
for (i = 0; i < 128; i++) {
    printf("%02x ", buf[i]);
}

You will also want to declare buf as unsigned char *; and you should also always check the return value of read().

