UNIX Input/Output
Working with Disk Files and the File System |
Prof. David Bernstein |
Computer Science Department |
bernstdh@jmu.edu |
off_t lseek(int fd, off_t offset, int whence);
fd
|
The file descriptor |
offset
|
The offset (in bytes) |
whence
|
The base point from which offset is to be interpreted |
Return | The new file offset; -1 on error |
whence
Values
SEEK_SET
|
The base is the beginning of the file (i.e., the file offset is set to offset n which must be non-negative) |
SEEK_CUR
|
The base is the current offset |
SEEK_END
|
The base is the size of the file |
// Obtain the current file offset current = lseek(fd, 0, SEEK_CUR); // Set the file offset to the start of the file lseek(fd, 0, SEEK_SET); // Set the file offset to the next byte after the end of the file lseek(fd, 0, SEEK_END);
// Save the current file offset original = lseek(fd, 0, SEEK_CUR); // Set the file offset to a particular value lseek(fd, offset, SEEK_SET); // Read from the new file offset size = read(fd, buffer, length); // Reset the file offset lseek(fd, original, SEEK_SET);
Unfortunately, this sequence of calls is not atmoic (i.e., might be interrupted)!
ssize_t pread(int fd, void* buffer, size_t count, off_t offset);
fd
|
The file descriptor to read from |
buffer
|
The ultimate location of the bytes in memory |
count
|
The maximum number of bytes to copy |
offset
|
The file offset to copy from |
Return | The number of bytes copied; 0 on EOF; -1 on error |
ssize_t pwrite(int fd, const void *buffer, size_t count, off_t offset
fd
|
The file descriptor to copy to |
buffer
|
The memory to copy from |
count
|
The maximum number of bytes to copy |
offset
|
The file offset to copy to |
Return | The number of bytes copied; -1 on error |