If you use a posix compatible compiler, you can also use stat() to get the filesize, allocate the buffer and read it in with fread at once.
Code:
#include <stdio.h>
#include <stdlib.h>
#include <sys/stat.h>
static void readfile(FILE *fp, size_t size);
int main(int argc, char **argv)
{
struct stat st;
FILE *fp = fopen(__FILE__, "rb");
if (fp != NULL && fstat(fileno(fp), &st) == 0)
{
readfile(fp, st.st_size);
}
if (fp != NULL)
fclose(fp);
return 0;
}
void readfile(FILE *fp, size_t size)
{
char *ptr = malloc(size+1);
if (ptr != NULL)
{
ptr[size] = '\0';
if (fread(ptr, size, 1, fp) == 1)
{
puts(ptr);
}
free(ptr);
}
}