开发者

Using fwrite on file descriptor / Convert file descriptor to file pointer

开发者 https://www.devze.com 2023-01-08 13:39 出处:网络
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.

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

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号