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
?
Use fdopen.
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()
.
精彩评论