fseek function-sets the position of the file stream position specifier

You can use the fseek function to set the position pointed to by the file stream position specifier. You can use it by reading the stdio.h header.

#include <stdio.h>
int fseek (FILE * fp, long offset, int origin);

The first argument is the file stream. The second argument is the relative position pointed to by the file stream position specifier. The third argument is used as the reference position. The third argument is the reference position. You can specify the beginning of the file with "SEEK_SET", the current position of the file with "SEEK_CUR", and the end of the file with "SEEK_END".

The main uses of the fseek function are when reading and writing files with fixed length data and when you want to get the file size.

Sample to get the file size

This is a sample to get the file size using the fseek function and ftell function.

#include <stdio.h>
#include <stdint.h>
#include <stdlib.h>

int main (void) {
  // Open the file
  const char * in_file = "input.txt";
  FILE * in_fp = fopen (in_file, "r");
  if (in_fp == NULL) {
    fprintf (stderr, "Can't open file%s\n", in_file);
    exit (1);
  }
  
  // Move the position specifier to the end of the file
  fseek (in_fp, 0, SEEK_END);
  
  // Get the position of the end of the file. This will be phi size.
  int32_t file_size = (int32_t) ftell (in_fp);
  
  printf("%d\n", file_size);
  
  // Close the file
  fclose (in_fp);
}

Input file. There is no newline at the end.

Hello World!

Output result. The file size has been obtained.

11 11

Associated Information