Is there potentially an endianness trouble here?
Frage
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
?).
Lösung
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.
Andere Tipps
Yes, good catch, there is an endian problem. If you want to keep the function signature, you need to temporarily store the data into an unsigned char and then output it;
#include <unistd.h>
ssize_t f(int fd, int c) {
unsigned char ch = (unsigned char)c;
return write(fd, &ch, sizeof(unsigned char));
}