I am reading and writing to sockets using fread() and fwrite(). These functions, I believe are for buffered input and output. Is there some way that I can disable buffering while still using these functions ?
Edit :
I am building a remote desktop application and the remote client seems to be "lagging a bit behind the server", and I dont have any idea what may be the reason... I thought it may be because of buffered read and write .. but using setvbuf didnt work.
By "lagging", I mean that the remote desktop client is running a few seconds behind the server. What the server is doing at a particular moment is reflected on the client side after a delay of some 15-20 seconds.
Also, I dont want to not-use-fread(), because it is a part of existing code. I don't want to modify it. I could eventually use write() and read(), but I would like to avoid it.
You can use setvbuf
to disable buffering for a specific file pointer:
setvbuf(fp, NULL, _IONBF, 0);
Mixing sockets with standard input is kind of tricky, as warned by Stevens. Here are a few quotes.
The problem problem with these latter three functions [fseek, fsetpos, rewing] is that they all call lseek, which fails on a socket.
The easiest way to handle this read-write problem is to open two standard I/O streams for a given socket: one for reading and one for writing.
One way around this [buffering problem] is to force the output stream to be line buffered by calling setvbuf. Another is to force each echoed line to be output by calling fflush after each call to fputs. But in practice, either of these solutions is still error-prone and may interact badly with the Nagle algorithm
In conclusion:
Try to stop using stdio
. It makes no sense to use stdio
and fread
and fwrite
. Use straight read
and write
instead. Stevens speaks of "line buffered" output because people use fgets
and fputs
with stdio