fix get_binary
This commit is contained in:
parent
bcea78a987
commit
86f3d5c9b9
@ -6,14 +6,15 @@ I/O module to assist with consuming data from files
|
|||||||
|
|
||||||
### get_binary
|
### get_binary
|
||||||
|
|
||||||
Reads a file at `path` and returns the contents as a char* buffer. The buffer is allocated inside the function and
|
Reads a file at `path` and returns the contents as a char* buffer. The `fsz` parameter stores the length of the
|
||||||
the user is responsible for freeing it when finished.
|
returned array. The buffer is allocated inside the function, so the user is responsible for freeing it when finished.
|
||||||
|
|
||||||
```c
|
```c
|
||||||
char *get_binary(const char *path);
|
char *get_binary(const char *path, size_t *fsz);
|
||||||
|
|
||||||
/* Usage */
|
/* Usage */
|
||||||
char *buf = get_binary("/home/evan/binfile");
|
size_t fsz = 0;
|
||||||
|
char *buf = get_binary("/home/evan/binfile", &fsz);
|
||||||
free(buf);
|
free(buf);
|
||||||
```
|
```
|
||||||
|
|
||||||
|
@ -3,7 +3,7 @@
|
|||||||
|
|
||||||
#include <stdlib.h>
|
#include <stdlib.h>
|
||||||
|
|
||||||
char *get_binary(const char *);
|
char *get_binary(const char *, size_t *fsz);
|
||||||
|
|
||||||
char *get_input(const char *);
|
char *get_input(const char *);
|
||||||
|
|
||||||
|
@ -26,22 +26,21 @@ static FILE* open_file(const char *path, size_t *fsz) {
|
|||||||
return fp;
|
return fp;
|
||||||
}
|
}
|
||||||
|
|
||||||
char *get_binary(const char *path) {
|
char *get_binary(const char *path, size_t *fsz) {
|
||||||
size_t fsz = 0;
|
FILE *fp = open_file(path, fsz);
|
||||||
FILE *fp = open_file(path, &fsz);
|
|
||||||
if (fp == NULL) {
|
if (fp == NULL) {
|
||||||
return NULL;
|
return NULL;
|
||||||
}
|
}
|
||||||
|
|
||||||
char *buf = NULL;
|
char *buf = NULL;
|
||||||
buf = malloc(fsz);
|
buf = malloc(*fsz);
|
||||||
if (buf == NULL) {
|
if (buf == NULL) {
|
||||||
fprintf(stderr, "Failed to malloc buf. Returning NULL\n");
|
fprintf(stderr, "Failed to malloc buf. Returning NULL\n");
|
||||||
fclose(fp);
|
fclose(fp);
|
||||||
return NULL;
|
return NULL;
|
||||||
}
|
}
|
||||||
|
|
||||||
fread(buf, 1, fsz, fp);
|
fread(buf, 1, *fsz, fp);
|
||||||
fclose(fp);
|
fclose(fp);
|
||||||
|
|
||||||
return buf;
|
return buf;
|
||||||
|
Loading…
x
Reference in New Issue
Block a user