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 −

  • FILE *stream: A pointer to a FILE object that identifies the stream.
  • long int offset: The number of bytes to move the file pointer.
  • int whence: The position from which the offset is added. It can have one of the following values:
    • 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]
    
    Advertisements