I've been using the read(2) and write(2) functions to read and write to a file given a file descriptor.
Is there any function like this that allows you to put an offset into the file for read/write?
Yes, you're looking for lseek
.
There are pread/pwrite functions that accept file offset:
ssize_t pread(int fd, void *buf, size_t count, off_t offset);
ssize_t pwrite(int fd, const void *buf, size_t count, off_t offset);
Yes. You use the lseek
function in the same library.
You can then seek to any offset relative to the start or end of file, or relative to the current location.
Don't get overwhelmed by that library page. Here are some simple usage examples and probably all most people will ever need:
lseek(fd, 0, SEEK_SET); /* seek to start of file */
lseek(fd, 100, SEEK_SET); /* seek to offset 100 from the start */
lseek(fd, 0, SEEK_END); /* seek to end of file (i.e. immediately after the last byte) */
lseek(fd, -1, SEEK_END); /* seek to the last byte of the file */
lseek(fd, -10, SEEK_CUR); /* seek 10 bytes back from your current position in the file */
lseek(fd, 10, SEEK_CUR); /* seek 10 bytes ahead of your current position in the file */
Good luck!
lseek()
and ye shall receive.
Yes, you can use lseek()
:
off_t lseek(int fd, off_t offset, int whence);
The
lseek()
function repositions the offset of the open file associated with the file descriptorfd
to the argumentoffse
t according to the directivewhence
as follows:
SEEK_SET
The offset is set to offset bytes.
SEEK_CUR
The offset is set to its current location plus offset bytes.
SEEK_END
The offset is set to the size of the file plus offset bytes.
来源:https://stackoverflow.com/questions/19780919/read-write-from-file-descriptor-at-offset