The general syntax for this function is:
The function supports three parameters:
- stream – Pointer to the file object.
- offset – Number of offset bytes from the start position.
- origin – Position where the offset values are added.
The fseek origin values include:
- SEEK_SET – Beginning of the file.
- SEEK_CUR – The current cursor position.
- SEEK_END – End of file.
The fseek function returns zero on success and a non-zero value on failure.
Suppose we have a text file with the contents as:
This is C language calling for you!
Are you going you going to answer?”
We can use SEEK_END to move the pointer to the end of the file. Consider the example code shown below:
The cursor moves to the end and prints the pointer position. Since we set the offset value after the end of the file to 0, it prints 91 as it pointer position.
To move to a specific position using fseek, we can simply use the SEEK_SET to move the specified number of bytes from the beginning of the file.
An example code is as shown:
In the above example, we tell the pointer to move 10 bytes. This should return 10 as the current pointer position.
This short tutorial has shown you how to use the fseek function in C. Check the manual to learn more.