First, this is wrong:
>char c = 1;
>while (c != EOF)
because EOF is an int and c is only a char. You must make c an int for this to work.
Also, you can do the loop control like this:
>while ((c = fgetc(f)) != EOF)
>realloc()
Don't pass the same pointer you are using the store the return from realloc as it's first arg. If realloc fails, it will return NULL, but the pointer in its first arg will still be valid. If you use the same pointer for both, you loose the address of the original memory block, and thereby create a leak.
>if ((buf = (char *) realloc(buf, ((&(*tmp) - &(*buf)) + sizeof(char)))) == NULL) return NULL;
This looks rather complicated for what it is. Can't you simplify the second arg to something like
>(tmp - buf) + sizeof(char)
(I'm not sure what you try to do, so maybe I'm wrong here).
As you are reading the whole file into memory, you could also use this method:
- Determine the size of the file (maybe using fseek())
- malloc that amount of bytes
- fread() the file into memory.
Here's a sample
Code:
char* LoadFile(char *FileName, long int *CharsRead)
{
/*
* Load a complete file into malloc'd memory
*
* Return a pointer to the start of the data, or NULL if error occurs.
* It is up to the caller to free the memory when it's finished with.
*
* CharsRead will be populated with the number of bytes read in.
*/
FILE *fp;
char *ptr;
long int FileSize;
*CharsRead = 0;
if ((fp = fopen(FileName, "rb")) == NULL)
{
perror (FileName);
return (NULL);
}
fseek(fp, 0, SEEK_END);
FileSize = ftell(fp);
fseek(fp, 0, SEEK_SET);
if ((ptr = malloc(FileSize)) == NULL)
{
perror ("Memory allocation failure!");
return (NULL);
}
if ((fread(ptr, FileSize, 1, fp)) != 1)
{
perror (FileName);
free(ptr);
ptr = NULL;
}
else *CharsRead = FileSize;
return (ptr);
} /* End of LoadFile *