Skip to content

Commit

Permalink
Improve read_whole_file()
Browse files Browse the repository at this point in the history
Move into os.c, declare and document in os.h
  • Loading branch information
quixotique committed Dec 19, 2013
1 parent 39b2f3a commit 21328e2
Show file tree
Hide file tree
Showing 3 changed files with 29 additions and 13 deletions.
21 changes: 21 additions & 0 deletions os.c
Expand Up @@ -162,3 +162,24 @@ ssize_t read_symlink(const char *path, char *buf, size_t len)
buf[nr] = '\0';
return nr;
}

ssize_t read_whole_file(const char *path, unsigned char *buffer, size_t buffer_size)
{
int fd = open(path, O_RDONLY);
if (fd == -1)
return WHYF_perror("open(%d,%s,O_RDONLY)", fd, alloca_str_toprint(path));
ssize_t ret;
struct stat stat;
if (fstat(fd, &stat) == -1)
ret = WHYF_perror("fstat(%d)", fd);
else if ((size_t)stat.st_size > buffer_size)
ret = WHYF("file %s (size %zu) is larger than available buffer (%zu)", alloca_str_toprint(path), (size_t)stat.st_size, buffer_size);
else {
ret = read(fd, buffer, buffer_size);
if (ret == -1)
ret = WHYF_perror("read(%d,%s,%zu)", fd, alloca_str_toprint(path), buffer_size);
}
if (close(fd) == -1)
ret = WHYF_perror("close(%d)", fd);
return ret;
}
8 changes: 8 additions & 0 deletions os.h
Expand Up @@ -125,4 +125,12 @@ int urandombytes(unsigned char *buf, size_t len);
*/
ssize_t read_symlink(const char *path, char *buf, size_t len);

/* Read the whole file into the given buffer. If the file will not fit into
* the buffer or if there is an error opening or reading the file, logs an
* error and returns -1. Otherwise, returns the number of bytes read.
*
* @author Andrew Bettison <andrew@servalproject.com>
*/
ssize_t read_whole_file(const char *path, unsigned char *buffer, size_t buffer_size);

#endif //__SERVAL_DNA__OS_H
13 changes: 0 additions & 13 deletions rhizome_bundle.c
Expand Up @@ -399,19 +399,6 @@ int rhizome_manifest_verify(rhizome_manifest *m)
return 1;
}

ssize_t read_whole_file(const char *path, unsigned char *buffer, size_t buffer_size)
{
int fd = open(path, O_RDONLY);
if (fd == -1)
return WHYF_perror("open(%s,O_RDONLY)", alloca_str_toprint(path));
ssize_t ret = read(fd, buffer, buffer_size);
if (ret == -1)
ret = WHYF_perror("read(%s,%zu)", alloca_str_toprint(path), buffer_size);
if (close(fd) == -1)
ret = WHY_perror("close");
return ret;
}

static void rhizome_manifest_clear(rhizome_manifest *m)
{
while (m->var_count) {
Expand Down

0 comments on commit 21328e2

Please sign in to comment.