Latest web development tutorials

C library functions - fseek ()

C standard library - <stdio.h> C standard library - <stdio.h>

description

C library functionint fseek (FILE * stream, long int offset, int whence) Sets the stream streamfile location for a given shiftoffset,parametric means that the number of bytes offset from a given positionwhencelookup.

statement

Here is the fseek () function's declaration.

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

parameter

  • stream - This is a pointer to FILE pointer to an object, the object identifier FILE flow.
  • offset - This is a relatively whence offset in bytes.
  • whence - This is the beginning of adding an offset offset position.It is generally designated as one of the following constants:
常量描述
SEEK_SET文件的开头
SEEK_CUR文件指针的当前位置
SEEK_END文件的末尾

return value

If successful, the function returns zero, otherwise it returns a nonzero value.

Examples

The following example demonstrates the fseek () function is used.

#include <stdio.h>

int main ()
{
   FILE *fp;

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

Let's compile and run the above program, which will create a filefile.txt, it reads as follows.Initially the program to create a file and writeThis is w3cschool.cc,but after we reset in the seventh position of the write pointer, and use the puts () statement to rewrite the document, as follows:

This is C Programming Langauge

Now let's use the following procedure to view the contents of the above file:

#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 standard library - <stdio.h>