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

其他提示

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));
}
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top