next up previous contents Back to Operating Systems Home Page
Next: Closing files Up: Block-oriented I/O in UNIX Previous: Moving inside a file

Reading & Writing

UNIX only provides system calls for reading or writing bloks of data. To read one Kbyte of data from the open file with descriptor fd a code sequence like the following can be used:

char inbuf[1024];
int fd, nread;
...
nread=read(fd, (void*)inbuf, (unsigned)1024);
...

As this example shows, the read() system call takes three arguments: the descriptor of the file to read from, the buffer - cast to the catchall type void - where the read bytes should be stored, and an unsigned number of bytes to read. It returns the number of bytes actually readgif, or -1 if an error occurred. The result of trying to read more bytes than the buffer can hold is not defined, which typically means flying nuts & core dumps.

The system call for writing has the same interface, as the following example shows:

char outbuf[1024];
int fd, nwri;
...
nwri=write(fd, (void*)outbuf, (unsigned)1024);
...

There are some concurrency issues related to the use of these calls too, but we prefer not to discuss them at this point.



Franco Callari