Easy Tutorial
❮ C Exercise Example88 C Function Sprintf ❯

C Library Function - fseek()

C Standard Library - <stdio.h>

Description

The C library function int fseek(FILE *stream, long int offset, int whence) sets the file position of the stream stream to the given offset offset, where the parameter offset indicates the number of bytes to seek from the given whence position.

Declaration

Here is the declaration for the fseek() function.

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

Parameters

Constant Description
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 zero if successful, otherwise it returns a non-zero value.

Example

The following example demonstrates the use of the fseek() function.

#include <stdio.h>

int main ()
{
   FILE *fp;

   fp = fopen("file.txt","w+");
   fputs("This is tutorialpro.org", fp);

   fseek( fp, 7, SEEK_SET );
   fputs(" C Programming Language", fp);
   fclose(fp);

   return(0);
}

Let's compile and run the above program, which will create a file file.txt with the following content. Initially, the program creates the file and writes This is tutorialpro.org, but then we reset the write pointer to the seventh position and rewrite the file using the puts() statement, resulting in the following content:

This is C Programming Language

Now, let's view 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);
}

C Standard Library - <stdio.h>

❮ C Exercise Example88 C Function Sprintf ❯