You can read a block of information from a file with the read
function. The data read is loaded directly into a buffer in memory.
The data can be binary as well as a text, but if the latter, no
terminating newline is added. The bytes read start at the current file
position; after reading them, read advances the file position to
immediately after the bytes read.
The read function takes three parameters. The first one is the
file descriptor from which data is to be read. The second is the buffer
in memory where the data read will be stored. The buffer is of type
void *, and can be an array or a chunk of space reserved with
malloc. The final parameter is of type size_t, and specifies
the number of bytes to read.
The return value of this function is of type ssize_t, and
represents the number of bytes actually read. This might be less than
the number of bytes requested if there are not enough bytes left in the
file or immediately available. Reading less than the number of bytes
requested does not generate an error.
If the number of bytes requested is not zero, a return value of zero
indicates the end of the file. This is also not an error. If you keep
calling read at the end of the file, it will simply keep
returning zero. If read returns at least one character, you
cannot tell whether the end of the file was reached from that
information, but read will return zero on the next read operation
if it was.
If there was an error, read returns -1. You can then check the
system variable errno for one of the following error conditions,
as well as the usual file name errors. (See Usual file name errors.)
The read function can also return some other error conditions in
errno that are mostly of interest to advanced C programmers.
(See Input and Output Primitives, for more information.)
EBADF
The file descriptor passed to read is not valid, or is not open
for reading.
EIO
There was a hardware error. (This error code also applies to more abstruse
conditions detailed in the GNU C Library manual.)