diff --git a/core/stream_file.c b/core/stream_file.c new file mode 100644 index 0000000..740141c --- /dev/null +++ b/core/stream_file.c @@ -0,0 +1,71 @@ +/* + * Copyright (c) 2026, Chloe M. + * Provided under the BSD-3 clause + */ + +#include +#include +#include +#include +#include +#include +#include "blobchain/memlib.h" +#include "blobchain/stream.h" + +int +stream_from_file(struct data_stream *stmp, const char *path) +{ + struct stat sb; + void *p; + ssize_t readlen; + int error, fd; + + if (stmp == NULL || path == NULL) { + errno = -EINVAL; + return -1; + } + + error = stat(path, &sb); + if (error < 0) { + perror("stat"); + return -1; + } + + fd = open(path, O_RDONLY); + if (fd < 0) { + perror("open"); + return -1; + } + + /* + * Now we want to allocate a whole block of memory to + * contain the entire file. + * + * XXX: For this reason, it is a good idea to only work with + * one file at a time to avoid saturating all of your RAM... + */ + p = xmalloc(sb.st_size); + stmp->length = sb.st_size; + stmp->data = p; + + readlen = read(fd, p, stmp->length); + if (readlen < 0) { + perror("read"); + close(fd); + free(p); + return -1; + } + + return 0; +} + +void +stream_destroy(struct data_stream *stmp) +{ + if (stmp == NULL) { + return; + } + + free(stmp->data); + stmp->length = 0; +} diff --git a/inc/blobchain/stream.h b/inc/blobchain/stream.h index afb0f87..5e9c523 100644 --- a/inc/blobchain/stream.h +++ b/inc/blobchain/stream.h @@ -19,4 +19,19 @@ struct data_stream { size_t length; }; +/* + * Obtain a stream from a file + * + * @stmp: Stream pointer result + * @path: Path of file to obtain stream from + * + * Returns zero on success + */ +int stream_from_file(struct data_stream *stmp, const char *path); + +/* + * Destroy a data stream + */ +void stream_destroy(struct data_stream *stmp); + #endif /* !BLOBCHAIN_STREAM_H */