Reading a file
This section describes the read subroutines.
Reading a file
| Subroutine | Description |
|---|---|
| read | Subroutine that copies a specified number of bytes from an open file to a specified buffer. The copy begins at the point indicated by the current offset. The number of bytes and buffer are specified by the NBytes and Buffer parameters. |
The read subroutine does the following:
- Ensures that the FileDescriptor parameter is valid and that the process has read permissions. The subroutine then gets the file table entry specified by the FileDescriptor parameter.
- Sets a flag in the file to indicate a read operation is in progress. This action locks other processes out of the file during the operation.
- Converts the offset byte value and the value of the NBytes variables into a block address.
- Transfers the contents of the identified block into a storage buffer.
- Copies the contents of the storage buffer into the area designated by the Buffer variable.
- Updates the current offset according to the number of bytes actually read. Resetting the offset ensures that the data is read in sequence by the next read process.
- Deducts the number of bytes read from the total specified in the NByte variable.
- Loops until the number of bytes to be read is satisfied.
- Returns the total number of bytes read.
The cycle completes when the file to be read is empty, the number of bytes requested is met, or a reading error is encountered during the process.
To avoid an extra iteration in the read loop, start read requests at the beginning of data block boundaries and to be multiples of the data block size. If a process reads blocks sequentially, the operating system assumes all subsequent reads will also be sequential.
During the read operation, the i-node is locked. No other processes are allowed to modify the contents of the file while a read is in progress. However the file is unlocked immediately on completion of the read operation. If another process changes the file between two read operations, the resulting data is different, but the integrity of the data structure is maintained.
#include <fcntl.h>
#include <sys/param.h>
main()
{
int fd;
int nbytes;
int nnulls;
int i;
char buf[PAGESIZE]; /*A convenient buffer size*/
nnulls=0;
if ((fd = open("foo",O_RDONLY)) < 0)
exit();
while ((nbytes = read(fd,buf,sizeof(buf))) > 0)
for (i = 0; i < nbytes; i++)
if (buf[i] == '\0';
nnulls++;
printf("%d nulls found\n", nnulls);
}