Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / C

ftell — C23 stream function

`ftell(stream)` from `<stdio.h>` obtains the current file position indicator. For a binary stream the result counts characters from the beginning of the file; for a text stream it is opaque information that can be passed to `fseek` with `SEEK_SET` to return to the same position.

Version: C23

Syntax

long int ftell(FILE *stream);

ftell(stream) from <stdio.h> obtains the current file position indicator. For a binary stream the result counts characters from the beginning of the file; for a text stream it is opaque information that can be passed to fseek with SEEK_SET to return to the same position.

The example writes five bytes, ABCDE, to a binary temporary file, so the first ftell produces 5. After fseek(..., 2L, SEEK_SET), the second produces 2 and the next read obtains C; the program prints 5 2 C.

The difference between two values for a text stream need not measure characters read or written. On failure the function returns -1L and stores an implementation-defined positive value in errno; always test that sentinel before using the result. A large-file position might not fit in long, and fgetpos/fsetpos is preferable when the multibyte parse state must be preserved too.

Examples

#include <stdio.h>
int main(void){FILE *stream=tmpfile();if(!stream)return 1;if(fwrite("ABCDE",1,5,stream)!=5){fclose(stream);return 1;}long end=ftell(stream);if(end<0||fseek(stream,2L,SEEK_SET)!=0){fclose(stream);return 1;}long middle=ftell(stream);int character=fgetc(stream);printf("%ld %ld %c\n",end,middle,character);return fclose(stream)==0?0:1;}

Result

5 2 C

The example writes five bytes, `ABCDE`, to a binary temporary file, so the first `ftell` produces `5`. After `fseek(..., 2L, SEEK_SET)`, the second produces `2` and the next read obtains `C`; the program prints `5 2 C`.

Sources