Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

...

However, the file position indicator returned by ftell() with a file opened in text mode is only useful in calls to fseek(). As such, the value of file_size may not necessarily be a meaningful measure of the number of characters in the file, and consequently, the amount of memory allocated may be incorrect, leading to a potential vulnerability.

Implementation Details

...

The value returned by ftell may not reflect the physical byte offset for streams opened in text mode, because text mode causes carriage return-linefeed translation. Use ftell with fseek to return to file locations correctly.

...

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

int main(void) {

  FILE *fp;
  char a[11];
  long offset;

  /* The contents of foo.txt are: 0123456789 repeated 10 times separated by line feeds (ie \n) */
  fp = fopen( "foo.txt", "r" );
  if (fp == NULL) {
    perror("fopen() error");
    exit(EXIT_FAILURE);
  }

  /* Read 10 (n-1) bytes */
  if (fgets(a, 11, fp) == NULL) {
    perror("fgets() error");
    fclose(fp);
    exit(EXIT_FAILURE);
  }

  offset = ftell(fp);
  if (offset == -1) {
    perror("ftell() error");
    fclose(fp);
    exit(EXIT_FAILURE);
  }

  printf("offset = %ld\n", offset);   /* Prints out 0.*/ 

  return 0;
}

...

However, 0 is incorrect; the correct value should be 10, as evident when the file is opened in binary mode rather than text mode.

Compliant Solution

...

This compliant solution uses fstat() instead to the size of the text file.

...

ISO/IEC 9899:2011 Section 7.21.9.2, "The fseek function", Section 7.21.3, "Files," and Section 7.21.9.4, "The ftell function"

Bibliography

[MSDN] "ftell"

[Open Group 2008]

...