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 ?).

War es hilfreich?

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 ints 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));
}
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top