Browse Source

Simplify read_whole_file and rename to read_file.

master
Richard Nyberg 18 years ago
parent
commit
3fb4e5a894
2 changed files with 20 additions and 29 deletions
  1. +19
    -27
      misc/subr.c
  2. +1
    -2
      misc/subr.h

+ 19
- 27
misc/subr.c View File

@@ -225,46 +225,38 @@ read_fully(int fd, void *buf, size_t len)
return 0; return 0;
} }


int void *
read_whole_file(void **out, size_t *size, const char *fmt, ...) read_file(const char *path, void *buf, size_t *size)
{ {
int err, fd; int fd, esave;
int didmalloc = 0; void *mem = NULL;
struct stat sb; struct stat sb;
va_list ap;


va_start(ap, fmt); if ((fd = open(path, O_RDONLY)) == -1)
err = vaopen(&fd, O_RDONLY, fmt, ap); return NULL;
va_end(ap); if (fstat(fd, &sb) == -1)
if (err != 0)
return err;
if (fstat(fd, &sb) != 0) {
err = errno;
goto error; goto error;
}
if (*size != 0 && *size < sb.st_size) { if (*size != 0 && *size < sb.st_size) {
err = EFBIG; errno = EFBIG;
goto error; goto error;
} }
*size = sb.st_size; *size = sb.st_size;
if (*out == NULL) { if (buf == NULL && (mem = malloc(sb.st_size)) == NULL)
if ((*out = malloc(*size)) == NULL) { goto error;
err = errno; if (buf == NULL)
goto error; buf = mem;
} if ((errno = read_fully(fd, buf, *size)) != 0)
didmalloc = 1;
}
if ((err = read_fully(fd, *out, *size)) != 0)
goto error; goto error;

close(fd); close(fd);
return 0; return buf;


error: error:
if (didmalloc) esave = errno;
free(*out); if (mem != NULL)
free(mem);
close(fd); close(fd);
return err; errno = esave;
return NULL;
} }


char * char *


+ 1
- 2
misc/subr.h View File

@@ -33,8 +33,7 @@ long rand_between(long min, long max);


int read_fully(int fd, void *buf, size_t len); int read_fully(int fd, void *buf, size_t len);
int write_fully(int fd, const void *buf, size_t len); int write_fully(int fd, const void *buf, size_t len);
__attribute__((format (printf, 3, 4))) void *read_file(const char *path, void *buf, size_t *size);
int read_whole_file(void **out, size_t *size, const char *fmt, ...);


char *find_btpd_dir(void); char *find_btpd_dir(void);




||||||
x
 
000:0
Loading…
Cancel
Save