Versions Compared

Key

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

...

This compliant solution uses the size provided by the POSIX fstat() function, rather than fseek() and ftell(), to obtain the size of the binary file.  This solution only works with regular files.

Code Block
bgColor#CCCCFF
langc
FILE *fp;
off_t file_size;
char *buffer;
struct stat stbuf;
int fd;
 
fd = open("foo.bin", O_RDONLY);
if (fd == -1) {
  /* Handle Error */
}
 
if ((fstat(fd, &ststbuf) != 0) || (!S_ISREG(ststbuf.st_mode))) {
  /* Handle Error */
}
 
file_size = stbuf.st_size;
 
buffer = (char*)malloc(file_size);
if (buffer == NULL) {
  /* Handle Error */
}

/* ... */ 

...