Fseek() seeks to and displays the specified byte in the specified file. - C File

C examples for File:File Operation

Introduction

To seek numbytes from the start of the file, origin should be SEEK_SET.

To seek from the current position, use SEEK_CUR,

To seek from the end of the file, use SEEK_END.

The fseek( ) function returns zero when successful and a nonzero value if an error occurs.

Demo Code

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

int main(int argc, char *argv[])
{
   FILE *fp;/*from  w ww.  j  a v  a 2  s  . co  m*/

   if (argc != 3) {
      printf("Usage: SEEK filename byte\n");
      exit(1);
   }

   if ((fp = fopen(argv[1], "rb")) == NULL) {
      printf("Cannot open file.\n");
      exit(1);
   }
   if (fseek(fp, atol(argv[2]), SEEK_SET)) {
      printf("Seek error.\n");
      exit(1);
   }

   printf("Byte at %ld is %c.\n", atol(argv[2]), getc(fp));
   fclose(fp);

   return 0;
}

Related Tutorials