core: stream: Add stream file operations
Signed-off-by: Chloe M. <chloe@mirocom.org>
This commit is contained in:
@@ -0,0 +1,71 @@
|
|||||||
|
/*
|
||||||
|
* Copyright (c) 2026, Chloe M.
|
||||||
|
* Provided under the BSD-3 clause
|
||||||
|
*/
|
||||||
|
|
||||||
|
#include <sys/stat.h>
|
||||||
|
#include <stdio.h>
|
||||||
|
#include <stdlib.h>
|
||||||
|
#include <errno.h>
|
||||||
|
#include <fcntl.h>
|
||||||
|
#include <unistd.h>
|
||||||
|
#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;
|
||||||
|
}
|
||||||
@@ -19,4 +19,19 @@ struct data_stream {
|
|||||||
size_t length;
|
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 */
|
#endif /* !BLOBCHAIN_STREAM_H */
|
||||||
|
|||||||
Reference in New Issue
Block a user