
- C Library - Home
- C Library - <assert.h>
- C Library - <complex.h>
- C Library - <ctype.h>
- C Library - <errno.h>
- C Library - <fenv.h>
- C Library - <float.h>
- C Library - <inttypes.h>
- C Library - <iso646.h>
- C Library - <limits.h>
- C Library - <locale.h>
- C Library - <math.h>
- C Library - <setjmp.h>
- C Library - <signal.h>
- C Library - <stdalign.h>
- C Library - <stdarg.h>
- C Library - <stdbool.h>
- C Library - <stddef.h>
- C Library - <stdio.h>
- C Library - <stdlib.h>
- C Library - <string.h>
- C Library - <tgmath.h>
- C Library - <time.h>
- C Library - <wctype.h>
- C Programming Resources
- C Programming - Tutorial
- C - Useful Resources
C Library - fseek() function
The C library fseek(FILE *stream, long int offset, int whence) function sets the file position of the stream to the given offset.This function is a part of the C Standard Library and is used for file handling.
Syntax
Following is the C library syntax of the fseek() function −
int fseek(FILE *stream, long int offset, int whence);
Parameters
This function accept three parameters −
- SEEK_SET: Beginning of the file.
- SEEK_CUR: Current position of the file pointer.
- SEEK_END: End of the file.
Return Value
The function returns 0 on success and Non-zero value on failure. The function also sets the errno to indicate the error.
Example 1: Moving to the Beginning of the File
This program opens a file and moves the file pointer to the beginning of the file before reading the first character.
Below is the illustration of the C library fseek() function.
#include <stdio.h> int main() { FILE *file = fopen("example1.txt", "r"); if (file == NULL) { perror("Error opening file"); return 1; } fseek(file, 0, SEEK_SET); char ch = fgetc(file); if (ch != EOF) { printf("First character in the file: %c\n", ch); } fclose(file); return 0; }
Output
The above code produces following result−
First character in the file: [First character of the file]
Example 2: Moving Backward from the Current Position
In this example, we move the file pointer to the 10th byte from the beginning and then moves it 3 bytes backward, resulting in the file pointer being at the 7th byte, from which it reads the character.
#include <stdio.h> int main() { FILE *file = fopen("example3.txt", "r"); if (file == NULL) { perror("Error opening file"); return 1; } fseek(file, 10, SEEK_SET); // Move to the 10th byte from the beginning fseek(file, -3, SEEK_CUR); // Move 3 bytes backward from the current position char ch = fgetc(file); if (ch != EOF) { printf("Character after moving backward: %c\n", ch); } fclose(file); return 0; }
Output
After execution of above code, we get the following result
Character after moving backward: [Character at position 7]