After installing the socket, is it better to use the read (2) and write (2) functions in the socket descriptor or to associate the stream with the socket descriptor using fdopen (3) and then use the stdio (3) functions?
int sfd = socket(PF_INET, SOCK_STREAM, 0); // setup the socket using sfd FILE * stream = fdopen(sfd, "r+"); // use fprintf, fscanf, etc
EDIT: I will also disable the stream
setbuf(stream, NULL)
To avoid the need to clean it, as indicated in the comments.
I use this approach because it allows me to reuse code written for FILE * streams, and I have the advantage of being able to use formatted strings. GNU seems to suggest that this is a good idea.
http://www.gnu.org/software/libc/manual/html_node/Streams-and-File-Descriptors.html
However, usually when I see code using sockets, a socket descriptor is used instead of a stream for all operations. Is there an advantage to using lower level functions?
szmoore
source share