tem as an index in a table of open files for your process, to know which file to use for reading or
writing. See figure 3.1.
File descriptors point to files used for standard input, standard output, and standard error.
All processes have three files open right from the start, by convention, even if they do not
open a single file. These open files have the file descriptors 0, 1, and 2. As you could see, file
descriptor 1 is used for data output and is called
, File descriptor 0 is used for
data input and is called
, File descriptor 2 is used for diagnostic (messages) output
and is called
To read an open file, you may call
. Here is the function declaration:
long read(int fd, void *buf, long nbytes)
It reads bytes from file descriptor
a maximum of
bytes and places the bytes read at
the address pointed to by
. The number of bytes read is the value returned. Read does not
guarantee that we would get as many bytes as we want, it reads what it can and lets us know.
This program reads some bytes from standard input and later writes them to standard output.
main(int , char* )
nr = read(0, buffer, sizeof buffer);
write(1, buffer, nr);
And here is how it works: