Why use a FILE stream when using a low-level function would be just as easy and would be faster? I don't really see any advantage of FILE streams over low-level I/O in this (aside from a reduced number of header files).
Code:
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
int main(void)
{
char buf[BUFSIZ], *file = NULL;
unsigned long size = 0;
int n_read;
int fd;
if((fd = open("somefile", O_RDONLY)) == -1)
{
puts("Couldn't open somefile for reading!");
exit(EXIT_FAILURE);
}
while((n_read = read(fd, buf, sizeof(buf))) != -1)
{
if(!(file = realloc(file, size+n_read)))
{
puts("Memory allocation error!");
exit(EXIT_FAILURE);
}
memcpy(file+size, buf, n_read);
size += n_read;
if(n_read < sizeof(buf))
break;
}
close(fd);
printf("Bytes read: %lu\n", size);
puts("\nFile dump:");
puts(file);
return EXIT_SUCCESS;
}