This blog is under construction

Friday 27 April 2012

fseek example in C

Header file:
    stdio.h

Synopsis:
     int fseek(FILE *stream, long offset, int origin);

Description:
     Its sets the file position for the given stream and the new position will be used for the subsequent read/write operations.  Returns 0 on success, non-zero on failure.


fseek function C program:


  #include<stdio.h>
  #include<string.h>
  int main() {
        char str[100];
        FILE *fp;
        fp = fopen("input.txt", "rb");

        memset(str, 0, 100);
        fseek(fp, -11, SEEK_END);
        fread(str, sizeof(char), 10, fp);
        printf("Last 10 characters in mastering-c.txt:\n");
        fputs(str, stdout);

        memset(str, 0, 100);
        fseek(fp, 0, SEEK_SET);
        fread(str, sizeof(char), 10, fp);
        printf("\n1st 10 characters in mastering-c.txt:\n");
        fputs(str, stdout);

        memset(str, 0, 100);
        fseek(fp, 10, SEEK_CUR);
        printf("\nMoves cursor 5 position forward and prints 5 char:\n");
        fread(str, sizeof(char), 5, fp);
        puts(str);
        return 0;
  }



  Output:
  jp@jp-VirtualBox:~/cpgms/exp$ cat input.txt
  This is fwrite example program
  Keep reading our blog
  Our youtube channel is programmingonline

  jp@jp-VirtualBox:~/cpgms/exp$ ./a.out
  Last 10 characters in mastering-c.txt:
  mingonline
  1st 10 characters in mastering-c.txt:
  This is fw
  Moves cursor 5 position forward and prints 5 char:
  le pr



No comments:

Post a Comment