lseek() function

Each opened file has a read and write position. When a file is opened, its read and write position usually points to the beginning of the file. If the file is opened in an append mode (such as O_APPEND), the read and write position will point to the end of the file. When read () or write(), the read and write position will increase accordingly. lseek() is used to control the read and write position of the file. It is used after open() opens the file.

head File

#include <sys/types.h>    
#include <unistd.h>

function prototype

off_t lseek(int fildes, off_t offset, int whence)

The parameter fildes is the open file descriptor, and
the parameter offset is the displacement number to move the reading and writing position according to the parameter whence.
The parameter whence is one of the following:
- SEEK_SET Seek from beginning of file + offset displacement
- SEEK_CUR Seek from current position + offset displacement amount
- SEEK_END Seek from end of file + offset displacement amount
When the whence value is SEEK_CUR or SEEK_END, the parameter offset allows negative values ​​to appear.

Example

When you want to move the read and write position to the beginning of the file:
lseek(int fildes, 0, SEEK_SET);
When you want to move the read and write position to the end of the file:
lseek(int fildes, 0, SEEK_END);
When you want to get the current file position:
lseek(int fildes, 0, SEEK_CUR);

return value

When the call is successful, the current read and write position is returned, which is how many bytes away from the beginning of the file.
If there is an error, -1 is returned, and errno will store the error code.

Guess you like

Origin blog.csdn.net/weixin_44280688/article/details/103892430