Here I have a method for reading the contents of a file into a buffer and returning whether or not it is successful.
Here is what I would like reviewed:
Speed: Am I reading in the file as fast as possible?
Bugs: Are there cases where my code could fail or give unexpected behavior?
Syntax/Styling: How does my code look? How could I make it look better? Anything I'm doing wrong syntax-wise?
int getFileContents(const char *file, void **contents, size_t *size)
{
// Open file for reading
int fd = open(file, O_RDONLY);
if (fd < 0) return -1;
off_t total = lseek(fd, 0, SEEK_END);
if (total < 0) return -1;
lseek(fd, 0, SEEK_SET);
ssize_t n, rest = total, readb = 0;
unsigned char buf[BUF_SIZE];
unsigned char *result = NULL;
// Read the whole file into memory
while (rest > 0) {
n = read(fd, buf, BUF_SIZE);
if (n < 0) {
close(fd);
free(result);
return -1;
}
unsigned char *tmp = (unsigned char*) realloc(result, readb + n);
if (!tmp) {
close(fd);
free(result);
return -1;
}
result = tmp;
memcpy(result + readb, buf, n);
readb += n;
rest -= n;
}
close(fd);
*contents = result;
*size = total;
return 0;
}