The fseek()
function is a file handling function in the C programming language used to set the file position indicator for a given file stream. It allows you to move the position within a file, both forward and backward, based on a specified offset.
Here’s the syntax of the fseek()
function:
int fseek(FILE *stream, long int offset, int origin);
The parameters of the fseek()
function are:
stream
: A pointer to theFILE
object that represents the file you want to manipulate.offset
: A value representing the number of bytes to offset from the origin. It can be positive, negative, or zero.origin
: An integer constant indicating the starting point for the offset calculation. It can have one of the following values:SEEK_SET
(0): The offset is calculated from the beginning of the file.SEEK_CUR
(1): The offset is calculated from the current position indicator.SEEK_END
(2): The offset is calculated from the end of the file.
The fseek()
function returns zero on success, and a non-zero value if an error occurs. Possible errors include an invalid file stream or an unsupported operation.
Here’s an example that demonstrates the usage of fseek()
:
#include <stdio.h> int main() { FILE *file = fopen("example.txt", "r"); if (file == NULL) { printf("Failed to open the file.\n"); return 1; } // Move the file position indicator to the 10th byte from the beginning of the file. fseek(file, 10, SEEK_SET); // Read and print the contents starting from the current position. int c; while ((c = fgetc(file)) != EOF) { putchar(c); } fclose(file); return 0; }
In this example, the program opens a file named “example.txt” in read mode. It then uses fseek()
to move the file position indicator to the 10th byte from the beginning of the file. Finally, it reads and prints the contents of the file starting from the current position.