C library function - fseek()

Advertisements


Description

The C library function int fseek(FILE *stream, long int offset, int whence) sets the file position of the stream to the given offset.

Declaration

Following is the declaration for fseek() function.

int fseek(FILE *stream, long int offset, int whence)

Parameters

  • stream -- This is the pointer to a FILE object that identifies the stream.

  • offset -- This is the number of bytes to offset from whence.

  • whence -- This is the position from where offset is added. It is specified by one of the following constants:

ConstantDescription
SEEK_SETBeginning of file
SEEK_CURCurrent position of the file pointer
SEEK_ENDEnd of file

Return Value

This function returns zero if successful, else it returns nonzero value.

Example

The following example shows the usage of fseek() function.

#include <stdio.h>

int main ()
{
   FILE *fp;

   fp = fopen("file.txt","w+");
   fputs("This is tutorialspoint.com", fp);
  
   fseek( fp, 7, SEEK_SET );
   fputs(" C Programming Langauge", fp);
   fclose(fp);
   
   return(0);
}

Let us compile and run the above program, this will create a file file.txt with the following content. Initially program creates file and writes This is tutorialspoint.com but later we reset the write pointer at 7th position from the begining and use puts() statement which over-write the file with the following content:

This is C Programming Langauge

Now let's the content of the above file using the following program:

#include <stdio.h>

int main ()
{
   FILE *fp;
   int c;

   fp = fopen("file.txt","r");
   while(1)
   {
      c = fgetc(fp);
      if( feof(fp) )
      {
          break ;
      }
      printf("%c", c);
   }
   fclose(fp);
   return(0);
}


Advertisements
Advertisements