Should I use file descriptors or streams to read / write to sockets

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?

+7
source share
1 answer

If you need more precise control and error handling, use read and write . If you don’t do this and prefer the stdio functions, use the FILE* wrapper.

One problem with using the FILE * shell is that you have no control over how and when data is actually written to the socket. This can lead to network inefficiencies and excessive delays (due to the Nagle algorithm interoperating with ACK latency) if you are not careful.

I would recommend using read and write directly if it is a high-performance internet application.

+3
source

All Articles