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.
SyntaxFollowing is the C library syntax of the fseek() function −
int fseek(FILE *stream, long int offset, int whence);Parameters
This function accept three parameters −
The function returns 0 on success and Non-zero value on failure. The function also sets the errno to indicate the error.
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]
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]
RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4