fix get_binary

This commit is contained in:
Evan Burkey 2023-05-03 14:46:38 -07:00
parent bcea78a987
commit 86f3d5c9b9
3 changed files with 10 additions and 10 deletions

View File

@ -6,14 +6,15 @@ I/O module to assist with consuming data from files
### get_binary
Reads a file at `path` and returns the contents as a char* buffer. The buffer is allocated inside the function and
the user is responsible for freeing it when finished.
Reads a file at `path` and returns the contents as a char* buffer. The `fsz` parameter stores the length of the
returned array. The buffer is allocated inside the function, so the user is responsible for freeing it when finished.
```c
char *get_binary(const char *path);
char *get_binary(const char *path, size_t *fsz);
/* Usage */
char *buf = get_binary("/home/evan/binfile");
size_t fsz = 0;
char *buf = get_binary("/home/evan/binfile", &fsz);
free(buf);
```

View File

@ -3,7 +3,7 @@
#include <stdlib.h>
char *get_binary(const char *);
char *get_binary(const char *, size_t *fsz);
char *get_input(const char *);

View File

@ -26,22 +26,21 @@ static FILE* open_file(const char *path, size_t *fsz) {
return fp;
}
char *get_binary(const char *path) {
size_t fsz = 0;
FILE *fp = open_file(path, &fsz);
char *get_binary(const char *path, size_t *fsz) {
FILE *fp = open_file(path, fsz);
if (fp == NULL) {
return NULL;
}
char *buf = NULL;
buf = malloc(fsz);
buf = malloc(*fsz);
if (buf == NULL) {
fprintf(stderr, "Failed to malloc buf. Returning NULL\n");
fclose(fp);
return NULL;
}
fread(buf, 1, fsz, fp);
fread(buf, 1, *fsz, fp);
fclose(fp);
return buf;