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;
10    char buffer[100];
11 
12    fp = fopen ("myfile.txt","rb");
13    if (fp == NULL) {
14      perror ("Error opening file");
15    }
16    else
17    {
18      fseek (fp, 0, SEEK_END);
19      size= ftell (fp);
20      
21      printf ("Size of myfile.txt: %ld bytes.\n",size);
22    rewind(fp); /* Same as fseek (fp, 0, SEEK_SET); */
23    
24    while((chunk = fread(buffer, 100, 1, fp)) > 0 && size) {
25    size -= chunk;
26    fwrite(buffer, chunk, 1, fp);
27    
28    }
29    fclose (pFile);
30    }
31    return 0;
32  }

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

 Vote 0

Similar topics related to this section

fopen, fdopen, write vs append mode, binary vs text mode, binary mode, fseek, ftell, rewind, fprintf, fscanf, fflush, poll, select, fcntl,

# C Programming Language (Prentice Hall Software)
# Let Us C Paperback - 2006 by Yashavant Kanetkar
# Understanding and Using C Pointers Core techniques for memory management
# Data Structures Using C and C++ Paperback - 1998
# Data Structures In C Paperback - August 11, 2008 by Noel Kalicharan