When you say something like
int n = 7;
write(fd, &n, sizeof(int));
you are taking the individual bytes corresponding to the integer n
and writing them out to the file descriptor fd
.
And that works just fine, unless what you wanted was a human readable representation of the integer n
. That's the representation you'd get if you had instead written
printf("%d\n", n);
It's printf
's job, when you use a format specifier like %d
, to create a human-readable string of characters corresponding to a data object.
So if you want to print an int
in a human-readable way, printf
is definitely your best bet. If for some reason you can't use printf
, you can use sprintf
to create an in-memory string, then use write
to write that out:
char tmpbuf[30];
sprintf(tmpbuf, "%d", n);
write(fd, tmpbuf, strlen(tmpbuf));
If for some reason you can't use sprintf
, you might be able to use itoa
:
char tmpbuf[30];
itoa(n, tmpbuf, 10);
write(fd, tmpbuf, strlen(tmpbuf));
However, the itoa
function is not standard. If you don't have it or can't use it, your last resort would be to convert an integer to its string representation yourself, by hand. That's such a common question that I'm not going to provide Yet Another answer to it here, but see the linked question, or this one.
You didn't ask, but if there's ever the related problem of printing a floating point number using write
, there are some hints in the comments at this question.