C ftell() Function Tutorial

In this section, we will learn what the ftell() function is and how it works in C.

C ftell() Function

Sometimes when we open a file and start to read and write on it, we want to know the current position from which we’re reading or writing to that file.

This is where we can use the `ftell()` function.

Via this function, we can get the current position of the target file.

Note: the prototype of the function is in the `stdio.h` header file, so we need to include the file in order to use the function.

C ftell() Function Syntax:

Here’s the prototype of the `ftell()` function:

long int ftell(FILE *stream)

C ftell() Function Parameters

The function only takes one argument and that is the address of the memory-space allocated to the FILE-structure of the target file.

C ftell() Function Return Value

The returned value of the function is of type `long` and it is the current position that we can read or write to the file.

Example: using ftell() function in C

#include <stdio.h>
#include <stdlib.h>

int main() {

    //Call the the fopen function in order to open the file in read mode.
    FILE *file = fopen("G:/fileOne.txt","r");
    //if there was a problem on opening the file, exit the program.
    if (file == NULL){
        printf("Could not open the file");
        exit(EXIT_FAILURE);

    }
    fseek(file, 7 ,SEEK_SET);
    char c;
    while((c = getc(file))!=EOF){
        printf("%d\n",ftell(file));

    }

    fclose(file);


    printf("\nDone\n");
    return 0;
}

Output:

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

Done

In this example, anytime we called the `getc` function, the current position in the file advanced one level and we simply sent this position to the output.

Facebook
Twitter
Pinterest
LinkedIn

Top Technologies