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.
fread() is part of the C library, and provides buffered reads. It is usually implemented by calling read() in order to fill its buffer.
An item of data is a sequence of bytes (not necessarily terminated by a null byte) of length size . fread stops appending bytes when nmemb items have been read, end of file has been reached, or an error has occurred.
Return Value. The fread() function returns the number of full items successfully read, which can be less than count if an error occurs, or if the end-of-file is met before reaching count. If size or count is 0, the fread() function returns zero, and the contents of the array and the state of the stream remain unchanged ...
bin','w'); fwrite(fileID,[1:9]); fclose(fileID); Read all the data in the file into a vector of class double . By default, fread reads a file 1 byte at a time, interprets each byte as an 8-bit unsigned integer ( uint8 ), and returns a double array.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With