Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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 "

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading