Versions Compared

Key

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

...

Code Block
bgColor#FFCCCC
langc
FILE *fp;
long file_size;
char *buffer;

fp = fopen("foo.bin", "rb");
if (fp == NULL) {
  /* Handle Error */
}

if (fseek(fp, 0 , SEEK_END) != 0) {
  /* Handle Error */
}

file_size = ftell(fp);
if (file_size == -1) {
  /* Handle Error */
}

buffer = (char*)malloc(file_size);
if (buffer == NULL) {
  /* Handle Error */
}

/* ... */ 

Compliant Solution (

...

POSIX ftello())

If the code needs to handle large files, it is preferable to use fseeko() and ftello() because for some implementations they can handle larger file offsets than fseek() and ftell().  If they are used, the file_size variable should have type off_t to avoid the possibility of overflow when assigning the return value of ftello() to it.  This solution only works with regular files.

...