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;
}

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

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

close(fd);
return 0;
return buf;

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

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 write_fully(int fd, const void *buf, size_t len);
__attribute__((format (printf, 3, 4)))
int read_whole_file(void **out, size_t *size, const char *fmt, ...);
void *read_file(const char *path, void *buf, size_t *size);

char *find_btpd_dir(void);



Loading…
Cancel
Save