How to use write() system call to write integer/float to a file descriptor?

Advertisements

For example:

int main()
{
    int out_fd = open("output.txt", O_CREAT|O_WRONLY|O_TRUNC, S_IRUSR|S_IWUSR|S_IRGRP|S_IROTH);

    int pid = getpid();

    if (out_fd != 1) {
        write(out_fd, &pid, sizeof(pid));
        write(out_fd, "\n", 1);
    }
    close(out_fd);
}

or

int out_fd = open("output.txt", O_CREAT|O_WRONLY|O_TRUNC, S_IRUSR|S_IWUSR|S_IRGRP|S_IROTH);

float f = 89.2;
if (out_fd != 1) {
    write(out_fd, &f, sizeof(f));
    write(out_fd, "\n", 1);
}
close(out_fd);

both produces unexpected results (garbled text), like "ff�B "

Although both can be conveniently solved with dprintf(), but can someone give me the write() system call version to write integers/floats to a fd?

Thanks!

>Solution :

write will just write out plain sequences of bytes. When you’re writing out a "native" datatype like int, what’s getting written into the file are the bytes which bits in succession will make up that type, in the machines byte and bit order (search for "Big Endian vs Little Endian" on that).

What you’re expecting is a textual representation of the numbers written out. So the first thing you have to do is to format the binary representation of the value into a textual representation. Which is exactly what snprintf and the likes are doing. Once you’ve got the textual representation you can write out that using write.

write itself however will do no data conversion for you whatsoever. It just takes whatever exists at the address and length you pass to it, and emit it to the file as-is.

Leave a ReplyCancel reply