6.18.25 fseek Function

Moves file pointer to a specific location.

Attention: This function is not implemented by MPLAB XC8.

Include

<stdio.h>

Prototype

int fseek(FILE * restrict stream, long offset, int mode);

Arguments

stream
stream in which to move the file pointer
offset
value to add to the current position
mode
type of seek to perform

Return Value

Returns 0 if successful; otherwise, returns a non-zero value and set errno.

Remarks

mode can be one of the following tabulated values.

ModeDescription
SEEK_SETseeks from the beginning of the file
SEEK_CURseeks from the current position of the file pointer
SEEK_ENDseeks from the end of the file

Example

#include <stdio.h>

int main(void)
{
  FILE *myfile;
  char s[70];
  int  y;
  myfile = fopen("afile.out", "w+");
  if (myfile == NULL)
    printf("Cannot open afile.out\n");
  else
  {
    fprintf(myfile, "This is the beginning, this is the middle and this is the end.");

    y = fseek(myfile, 0L, SEEK_SET);
    if (y)
      perror("Fseek failed");
    else
    {
      fgets(s, 22, myfile);
      printf("\"%s\"\n\n", s);
    }

    y = fseek(myfile, 2L, SEEK_CUR);
    if (y)
      perror("Fseek failed");
    else
    {
      fgets(s, 70, myfile);
      printf("\"%s\"\n\n", s);
    }

    y = fseek(myfile, -16L, SEEK_END);
    if (y)
      perror("Fseek failed");
    else
    {
      fgets(s, 70, myfile);
      printf("\"%s\"\n", s);
    }
    fclose(myfile);
  }
}

Example Output

"This is the beginning"

"this is the middle and this is the end."

"this is the end."

Example Explanation

The file afile.out is created with the text, “This is the beginning, this is the middle and this is the end.”

The function fseek uses an offset of zero and SEEK_SET to set the file pointer to the beginning of the file. fgets then reads 22 characters which are “This is the beginning,” and adds a null character to the string.

Next, fseek uses an offset of two and SEEK_CURRENT to set the file pointer to the current position plus two (skipping the comma and space). fgets then reads up to the next 70 characters. The first 39 characters are “this is the middle and this is the end.” It stops when it reads EOF and adds a null character to the string.

Finally, fseek uses an offset of negative 16 characters and SEEK_END to set the file pointer to 16 characters from the end of the file. fgets then reads up to 70 characters. It stops at the EOF after reading 16 characters “this is the end,” and adds a null character to the string.