ftell

From Get docs
< File input/outputC/docs/latest/io/ftell


ftell

Defined in header <stdio.h>
long ftell( FILE *stream );

Returns the file position indicator for the file stream stream.

If the stream is open in binary mode, the value obtained by this function is the number of bytes from the beginning of the file.

If the stream is open in text mode, the value returned by this function is unspecified and is only meaningful as the input to fseek().

Parameters

stream - file stream to examine

Return value

File position indicator on success or EOF if failure occurs.

On error, the errno variable is set to implementation-defined positive value.

Example

ftell with error checking.

#include <stdio.h>
#include <stdlib.h>
 
int main(void)
{
    /* Prepare an array of f-p values. */
    #define SIZE 5
    double A[SIZE] = {1.,2.,3.,4.,5.};
    /* Write array to a file. */
    FILE * fp = fopen("test.bin", "wb");
    fwrite(A,sizeof(double),SIZE,fp);
    fclose (fp);
 
    /* Read the f-p values into array B. */
    double B[SIZE];
    fp = fopen("test.bin","rb");
    long int pos = ftell(fp);   /* position indicator at start of file */
    if (pos == -1L)
    {
       perror("ftell()");
       fprintf(stderr,"ftell() failed in file %s at line # %d\n", __FILE__,__LINE__-4);
       exit(EXIT_FAILURE);
    }
    printf("%ld\n", pos);
 
    int ret_code = fread(B,sizeof(double),1,fp);   /* read one f-p value */
    pos = ftell(fp);   /* position indicator after reading one f-p value */
    if (pos == -1L)
    {
       perror("ftell()");
       fprintf(stderr,"ftell() failed in file %s at line # %d\n", __FILE__,__LINE__-4);
       exit(EXIT_FAILURE);
    }
    printf("%ld\n", pos);
    printf("%.1f\n", B[0]);   /* print one f-p value */
 
    return EXIT_SUCCESS; 
}

Output:

0
8
1.0

References

C11 standard (ISO/IEC 9899:2011):

  • 7.21.9.4 The ftell function (p: 337-338)

C99 standard (ISO/IEC 9899:1999):

  • 7.19.9.4 The ftell function (p: 303-304)

C89/C90 standard (ISO/IEC 9899:1990):

  • 4.9.9.4 The ftell function

See also

gets the file position indicator

(function)

moves the file position indicator to a specific location in a file

(function)

moves the file position indicator to a specific location in a file

(function)

© cppreference.com
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.
http://en.cppreference.com/w/c/io/ftell