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?
To access a text file we have to create a filehandle that will make an offset at the beginning of the text file. Simply said, offset is the position of the read/write pointer within the file. offset is used later on to perform operations within the text file depending on the permissions given, like read, write, etc.
write() : Will write data to the file at the offset specified. If the write is past the end-of-file, the file will be resized with padding zeros.
A successful read() changes the file offset by the number of bytes read. If read() is successful and nbyte is greater than zero, the access time for the file is updated.
An offset into a file is simply the character location within that file, usually starting with 0; thus "offset 240" is actually the 241st byte in the file.
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!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With