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.


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);


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()

Share this Tutorial / Exercise on : Facebook and Twitter

C Programming: Tips of the Day

What's an object file in C?

An object file is the real output from the compilation phase. It's mostly machine code, but has info that allows a linker to see what symbols are in it as well as symbols it requires in order to work. (For reference, "symbols" are basically names of global objects, functions, etc.)

A linker takes all these object files and combines them to form one executable (assuming that it can, i.e.: that there aren't any duplicate or undefined symbols). A lot of compilers will do this for you (read: they run the linker on their own) if you don't tell them to "just compile" using command-line options. (-c is a common "just compile; don't link" option.)

Ref : https://bit.ly/3CbzF8M