Overview

file is like byte array located in secondary memory device. Programmer can seek to any offset of an array by changing offset. However seeking to a file offset is not the same as the size of a file often too large to store in primary memory. File functions works on current file position. This position can be changed by fseek. Programmer need to provide a desired offset and origin.


FSEEK

Fseek allows programmer to change current file position to a particulate offset with reference to origin.

Syntax

int fseek ( FILE * fp, long int offset, int origin );

Parameters

  • fp - Pointer to a FILE object that identifies the stream.
  • offset - Number of bytes to offset from origin.
  • origin - Position used as reference for the offset. It is specified by one of the following constants.
    • SEEK_SET - Beginning of file
    • SEEK_CUR - Current position of the file pointer
    • SEEK_END - End of file

Return Value

If successful, the function returns zero. Otherwise, it returns non-zero value. If a read or write error occurs, the error indicator (ferror) is set.

FTELL

Returns the current value of the position indicator of the file.

SYNTAX

long int ftell ( FILE * fp );

Parameters

fp - Pointer to a FILE object that identifies the stream.

Return Value

On success, the current value of the position indicator is returned. On failure, -1L is returned, and errno is set to a system-specific positive value.

REWIND

Sets the position indicator associated with stream to the beginning of the file.

Syntax

void rewind ( FILE * fp );

Parameters

fp - Pointer to a FILE object that identifies the stream.

Return Value

none

fseek, ftell, rewind example


/* fseek, ftell, rewind example : getting size of a file */
#include <stdio.h>

int main ()
{
  FILE * fp;
  long size;
  long chunk;
  char buffer[100];

  fp = fopen ("myfile.txt","rb");
  if (fp == NULL) {
    perror ("Error opening file");
  }
  else
  {
    fseek (fp, 0, SEEK_END);
    size= ftell (fp);
    
    printf ("Size of myfile.txt: %ld bytes.\n",size);
  rewind(fp); /* Same as fseek (fp, 0, SEEK_SET); */
  
  while((chunk = fread(buffer, 100, 1, fp)) > 0 && size) {
  size -= chunk;
  fwrite(buffer, chunk, 1, fp);
  
  }
  fclose (pFile);
  }
  return 0;
}

About our authors: Team EQA

You have viewed 1 page out of 248. Your C learning is 0.00% complete. Login to check your learning progress.

Learn on Youtube

#