In the previous example with N = 8, read will read 8 bytes each time it is called
read(fd, buf, N)
except:
-
The last call will return 0 (end of file)
-
Unless the file size is a multiple of N, the next to last call will have fewer than N bytes left to read.
So the return value of read will be N until possibly the next to last call when it will be short and return a smaller value of actual bytes read.
The read and write functions can also be used to read/write data accross a network.
Because of network delays, a read operation may return a short read (fewer than the requested number of bytes) even though more bytes will be/are sent.
In this case it is necessary to keep calling read to get more bytes until
- The requested number of bytes, N, have been read or
- "end of file" each reached.
However, for a network connection, 0 is returned ("end of file") only when the connection is closed at the end that is writing.