ftell() | fseek() in C

ftell() function c

Functions ftell() and fseek() are important in a program performing file manipulations. Function ftell() returns the current position of the file pointer in a stream. The return value is 0 or a positive integer indicating the byte offset from the beginning of an open file. A return value of -1 indicates an error. Prototype of this function is as shown below

long int ftell(FILE *fp);

fseek() function in c

This function positions the next I/O operation on an open stream to a new position relative to the current position

int fseek(FILE *fp, long int offset, int origin);

Here fp is the file pointer of the stream on which I/O operations are carried on, offset is the number of bytes to skip over. The offset can be either positive or negative, denting forward or backward movement in the file. origin is the position in the stream to which the offset is applied, this can be one of the following constants

SEEK_SET : offset is relative to beginning of the file
SEEK_CUR : offset is relative to the current position in the file
SEEK_END : offset is relative to end of the file

Example of ftell() and fseek()

#include <stdio.h>
#include <stdlib.h>
char buffer[11];
int position;
main ()
 FILE *file_ptr;
 int num;
 if ((file_ptr = fopen("test_file", "w+f 10"))
== NULL)
printf("Error opening test_file \n");
 fputs("1111111111", file_ptr);
 fputs("2222222222", file_ptr);
 if ( (position = fseek(file_ptr, 10, SEEK_SET)) != 0)
 printf("Error in seek operation: errno \n");
 num = 11;
 fgets(buffer, num, file_ptr);
 printf("The record is %s\n", buffer);

The output from the preceding program

The record is 2222222222

Leave a Comment