commit 8375c04910e59654bc4fee4fbe8a820e1d3f839d
parent 31267a8f4d0871b341811b124d2f427c3fd96a48
Author: sin <sin@2f30.org>
Date: Thu, 17 Dec 2015 11:54:08 +0000
Add readfile()
Diffstat:
2 files changed, 27 insertions(+), 0 deletions(-)
diff --git a/sbtd.h b/sbtd.h
@@ -43,3 +43,4 @@ uint8_t hex2int(int);
uint8_t *hex2bin(const char *, uint8_t *, size_t);
char *bin2hex(const uint8_t *, char *, size_t);
void sha1sum(uint8_t *, unsigned long, uint8_t *);
+int readfile(char *, char **, size_t *);
diff --git a/util.c b/util.c
@@ -14,10 +14,15 @@
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
+#include <sys/types.h>
+#include <sys/stat.h>
+
#include <ctype.h>
#include <err.h>
+#include <fcntl.h>
#include <stdint.h>
#include <stdlib.h>
+#include <unistd.h>
#include "sbtd.h"
#include "sha1.h"
@@ -96,3 +101,24 @@ sha1sum(uint8_t *b, unsigned long n, uint8_t *md)
sha1_update(&ctx, b, n);
sha1_sum(&ctx, md);
}
+
+int
+readfile(char *file, char **b, size_t *n)
+{
+ struct stat sb;
+ int fd;
+
+ if ((fd = open(file, O_RDONLY)) < 0)
+ return -1;
+ if (fstat(fd, &sb) < 0) {
+ close(fd);
+ return -1;
+ }
+ *b = emalloc(*n = sb.st_size);
+ if (read(fd, *b, *n) != (ssize_t)*n) {
+ close(fd);
+ return -1;
+ }
+ close(fd);
+ return 0;
+}