Question

I want to read a file with some hexadecimals values. Such as this one :

^@\352\203\363

Or this when you put emacs in hexl-mode :

00ea 83f3

Here's a link to my file i'm trying to open : http://www.partage-facile.com/0L9FOY7ERB/toto.cor.html

Now here's my main where I try to read and print it :

#include <stdio.h>
#include <unistd.h>
#include <fcntl.h>

int     main(int ac, char **av)
{
     int fd;
     char tmp[4];

     if ((fd = open(av[1], O_RDONLY)) == -1)
     {
        printf("Open failed.\n");
        return (-1);
     }
     if ((read(fd, tmp, 4)) == -1)
     {
        printf("Read failed.\n");
        return (-1);
     }
     printf("%s", tmp); /* Here I don't know really what to do to print. */
     if ((close(fd)) == -1)
     {
        printf("Close failed.\n");
        return (-1);
     }
     return (0);
}

But it print me nothing, just blank. And if I try to print with printf (with flags like %x for hex it does randoms values)

Was it helpful?

Solution

The reason it doesn't print anything is that the first byte is null, which printf("%s") considers to mean "end of string". And if there had been no null bytes in the data, printf wouldn't have known where to stop, causing an overrun.

What you have in tmp is not a C string, just an array of 4 bytes. You can print them with something like this:

printf("%02x %02x %02x %02x", tmp[0], tmp[1], tmp[2], tmp[3]);

%x is the format specifier for hexadecimal integers, 2 is the field length and 0 means that the value should be zero-prefixed if it's shorter that the field length, i.e. the value 1 should be printed as 01 etc.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top