I would like to write a function such as putchar
, with the help of write
function.
#include <unistd.h>
ssize_t f(int fd, int c) {
return write(fd, &c, 1);
}
But I think there could be an endianness problem here, isn't it ? So should I use sizeof (int)
? I am a bit confused, I don't know how to process (need a cast to unsigned char
?).
Yes, there is potentially an endianness problem here. The cure is to pass c
as an unsigned char
rather than as an int
.
ssize_t
f(int fd, unsigned char c)
{
return write(fd, &c, 1);
}
The <stdio.h>
routines work with int
s mostly for historical reasons. They are very old, and contain many interface design decisions that would be considered incorrect nowadays. Do not use them as a template.