Reading files at a low level
You can read a block of information from a file with the
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.
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
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
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
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
errno for one of the following error conditions,
as well as the usual file name errors. (See Usual file name errors.)
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.)
- The file descriptor passed to
readis not valid, or is not open for reading.
- There was a hardware error. (This error code also applies to more abstruse conditions detailed in the GNU C Library manual.)
See Writing files at a low level, for a code example that uses the