w3resource

C ftell() function

C library function - ftell()

The ftell() function is used to obtain the current value of the file-position indicator for the stream pointed to by stream.

Syntax:

long int ftell(FILE *stream)

ftell() Parameters:

Name Description Required /Optional
stream The opened (via fopen) stream. Required

Return value from ftell()

  • The ftell() function returns the current file position. On error, ftell() and ftello() return –1, cast to long and off_t respectively, and set errno to a nonzero value.

Example: ftell() function

#include  <stdio.h>
#define NUM_CHAR   6
#define NUM_ALPHA  26

int main(void)
{
  FILE * stream;
  int i;
  char ch; 
  char buffer[NUM_ALPHA];
  long position;
 
  if (( stream = fopen("test.txt", "r")) != NULL )
  {
    /* read into buffer */
    for ( i = 0; ( i  < NUM_ALPHA/2 ) && ((buffer[i] = fgetc(stream)) != EOF ); ++i )
        if (i==NUM_CHAR-1)  /* We want to be able to position the   */
                                     /* file pointer to the character in */
                                     /* position NUM_CHAR                */
           position = ftell(stream);
 
    buffer[i] = '\0';
  } 
   printf("Current file position is %d\n", position); 
   printf("Buffer contains: %s\n", buffer);
}

Output:

Current file position is 6
Buffer contains: C programming

Errors: The value of error number can be set to:

Value Meaning
ENODEV Operation was attempted on a wrong device.
ENOTOPEN The file is not open.
ENUMMBRS The file is open for multi-member processing.
ENUMRECS Too many records.
ERECIO The file is open for record I/O.
ESTDERR stderr cannot be opened.
ESTDIN stdin cannot be opened.
ESTDOUT stdout cannot be opened.
EIOERROR A non-recoverable I/O error occurred.
EIORECERR A recoverable I/O error occurred.

C Programming Code Editor:

Contribute your code and comments through Disqus.

Previous C Programming: C fsetpos()
Next C Programming: C fwrite()



Follow us on Facebook and Twitter for latest update.