Example (ftell -- Get Current Position)

This example opens a file for reading. It reads enough characters to fill half of the buffer and prints out the position in the stream and the buffer.

#include <stdio.h>
#define FILENAME "myfile.dat"
#define NUM_ALPHA  26
#define NUM_CHAR    6
int main(void)
{
  FILE *stream;
  int i;
  char ch;
  char buffer[NUM_ALPHA];
  long position;
  if (( stream = fopen("FILENAME", "r")) != NULL )
  {
    /* read into buffer */
    for ( i = 0; ( i < NUM_ALPHA/2 ) &&
           ((buffer[i] = fgetc(stream)) != EOF ); ++i )
        if (i==NUM_CHAR-1)  /* We want to be able to position the   */
                            /* file pointer to the character in     */
                            /* position NUM_CHAR                    */
           position = ftell(stream);
           printf("Current position of the file is stored.\n");
        }
    buffer[i] = '\0';
    fseek(stream, position, SEEK_SET);
    ch = fgetc (stream);  /* get the character at position NUM_CHAR */
    printf("The character in position NUM_CHAR is '%c'.\n", ch);
    fclose(stream);
  }
  else
    perror("Error opening myfile");
  return 0;
}