#include #include #include #include extern errno; char *loadfile(path) char *path; { /* Opens file path, reads contents into malloc'd buffer, * appends null character to buffer, returns ptr to buffer. * Returns NULL if can't open/read file or can't malloc space. * The cases can be distinguished by errno=0 for latter case. * Comment: the file is assumed to be a "normal file"; i.e. * a single read will return all data in the file. */ struct stat statbuf; char *data; char *malloc(); int fd; if (stat(path, &statbuf) == -1) return NULL; data = malloc(statbuf.st_size+1); if (data == NULL) { errno = 0; return NULL; } data[statbuf.st_size] = '\0'; fd = open(path, O_RDONLY); if (fd == -1) { (void) free(data); return NULL; } if (read(fd, data, statbuf.st_size) != statbuf.st_size) { (void) free(data); return NULL; } return data; }