MULE 0.0.1
Multi-Use Library Essentials
Loading...
Searching...
No Matches
03_file.c

Read a whole file into a Str, and tell a read error from out of memory.

/* Str on its own: read a whole file into memory. */
#include "mem/mem.c"
#include "str/str.c"
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char **argv) {
const char *path = argc > 1 ? argv[1] : "data/pg2554.txt";
FILE *f = fopen(path, "rb");
if (f == NULL) {
perror(path);
return EXIT_FAILURE;
}
Str text = { 0 };
bool ok = str_append_file(&text, f);
bool read_error = ferror(f);
fclose(f);
if (!ok) {
fprintf(stderr, "%s: %s\n", path,
read_error ? "read error" : "out of memory");
return EXIT_FAILURE;
}
printf("%s: %zu bytes\n", path, text.len);
str_free(&text);
return EXIT_SUCCESS;
}
size_t len
Bytes of content, excluding the terminator.
Definition str.h:66
void str_free(Str *s)
Free the buffer and reset s to the zero state.
Definition str.c:50
bool str_append_file(Str *s, FILE *f)
Append everything left to read from f.
Definition str.c:156
Owned, growable byte string.
Definition str.h:64