C File I/O Operations : ftell()

The ftell() function returns the current value of the file position of the given file stream. The syntax of ftell() function is as follows :
 long int ftell(FILE *fp);
Where fp is the file pointer.

In the case of binary files, the value returned by the ftell() function indicates the number of bytes from the beginning of the file. But for text files, the returned value may not be meaningful except as an argument to fseek() because of possible character translations, such as carriage return/line-feeds being substituted for newlines, which affect the apparent size of the file.

Now lets take a look at some examples of ftell() function :

With Binary Files :
#include <stdio.h>
#include <string.h>

struct bookDB {
  char name[20];
  char author[20];
  int price;
};

int main() {
  int len;
  struct bookDB b1;
  FILE *fp;
  fp = fopen("books.dat", "wb");

  strncpy(b1.name, "C Programming", 20);
  strncpy(b1.author, "Dennis Ritchie", 20);
  b1.price = 250;
  fwrite(&b1, sizeof(b1), 1, fp);

  strncpy(b1.name, "C Sockets", 20);
  strncpy(b1.author, "John Forgers", 20);
  b1.price = 230;
  fwrite(&b1, sizeof(b1), 1, fp);
  fclose(fp);
  printf("File written successfully.\n");

  fp = fopen("books.dat", "rb");
  fseek(fp, 0, SEEK_END);
  len = ftell(fp);
  printf("Length of the file is : %d bytes.\n", len);
  return 0;
}
Output :

File written successfully.
Length of the file is : 88 bytes.

With Text Files :
 #include <stdio.h>

int main() {
  int len;
  char str[] = ("Hello world, This is Sample Text.\n");
  FILE *fp = fopen("myfile.txt", "w");
  fputs(str, fp);
  fclose(fp);
  printf("String written successfully into myfile.txt.\n");

  fp = fopen("myfile.txt", "r");
  fseek(fp, 0, SEEK_END);
  len = ftell(fp);
  printf("Length of file is %d bytes.\n", len);
  return 0;
}
Output :

String written successfully into myfile.txt.
Length of file is 34 bytes.

Topics :