views:

122

answers:

2

Lately, I've been working on some small data serialization demos. However, I was wondering how to transfer binary data from a structure into a file descriptor.

I am aware that the only (simple) way to do this is through fwrite (if write does this, then please say so), so is there either:

A) An fwrite call to use on file descriptors?

or

B) A way to create a FILE * around an existing file descriptor/socket, like the opposite of fileno?

+3  A: 

Use fdopen.

Matt Joiner
This kind of answer makes me wish I didn't have to wait 8 more minutes to accept it.Thanks!
new123456
Short and sweet. I'd add more but if you had problems or questions using fdopen, now that would be another question. :)
Matt Joiner
Nah, man pages tend to be really helpful. The problem, sometimes, is finding them. Besides, errno.h is usually verbose enough.
new123456
A: 

There are answers for both A) and B):

A) Yes, write() for a file descriptor is analagous to fwrite() for a file pointer:

if (fwrite(&foo, sizeof foo, 1, fp) < 1)
     /* Not successful */

or

if (write(fd, &foo, sizeof foo) < sizeof foo)
    /* Not immediately successful */

B) As Matt Joiner says, fdopen() is the inverse of fileno().

caf
Short `write` need not mean unsuccessful. The only failure case is when it returns -1. Certain types of fd's only support certain write lengths at a time, so in general you'll have to loop until all the data is written. For this reason, `fdopen` and `fwrite` are more convenient (they'll do it for you).
R..
@R.: Yes, absolutely agreed, on all points.
caf