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

Follow us on Facebook and Twitter for latest update.

C Programming: Tips of the Day

Reading a string with scanf :

An array "decays" into a pointer to its first element, so scanf("%s", string) is equivalent to scanf("%s", &string[0]). On the other hand, scanf("%s", &string) passes a pointer-to-char[256], but it points to the same place.

Then scanf, when processing the tail of its argument list, will try to pull out a char *. That's the Right Thing when you've passed in string or &string[0], but when you've passed in &string you're depending on something that the language standard doesn't guarantee, namely that the pointers &string and &string[0] -- pointers to objects of different types and sizes that start at the same place -- are represented the same way.

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