openreadclose.c (584B) download
1#ifndef EMBEDDED
2#define _FILE_OFFSET_BITS 64
3#include <unistd.h>
4#include <fcntl.h>
5#include <stdlib.h>
6#endif
7
8int openreadclose(char *fn, char **buf, size_t *len) {
9 int fd=open(fn,O_RDONLY);
10 if (fd<0) return -1;
11 if (!*buf) {
12 off_t o = lseek(fd, 0, SEEK_END);
13 if (o < 0 || o > 0x7fffffff) goto error; // impose sanity limits
14 *len = o;
15 *buf=(char*)malloc(*len+1);
16 if (!*buf) {
17error:
18 close(fd);
19 return -1;
20 }
21 }
22 *len=pread(fd,*buf,*len,0);
23 if (*len == (unsigned long)-1)
24 (*buf)[0]=0;
25 else
26 (*buf)[*len]=0;
27 return close(fd);
28}