Helper darr functions to read/write bytes from FILE *

This commit is contained in:
2023-10-21 23:23:13 +01:00
parent dcedb70a5c
commit 903ae3ab04
2 changed files with 25 additions and 0 deletions

View File

@@ -10,6 +10,7 @@
* Description: Dynamically sized byte array
*/
#include <assert.h>
#include <malloc.h>
#include <string.h>
@@ -56,3 +57,23 @@ byte darr_at(darr_t *darr, size_t index)
return 0;
return darr->data[index];
}
void darr_write_file(darr_t *bytes, FILE *fp)
{
size_t size = fwrite(bytes->data, bytes->used, 1, fp);
fclose(fp);
assert(size == 1);
}
darr_t darr_read_file(FILE *fp)
{
darr_t darr = {0};
fseek(fp, 0, SEEK_END);
long size = ftell(fp);
darr_init(&darr, size);
fseek(fp, 0, SEEK_SET);
size_t read = fread(darr.data, size, 1, fp);
fclose(fp);
assert(read == 1);
return darr;
}

View File

@@ -13,6 +13,7 @@
#ifndef DARR_H
#define DARR_H
#include <stdio.h>
#include <stdlib.h>
#include "./base.h"
@@ -32,4 +33,7 @@ void darr_append_byte(darr_t *, byte);
void darr_append_bytes(darr_t *, byte *, size_t);
byte darr_at(darr_t *, size_t);
void darr_write_file(darr_t *, FILE *);
darr_t darr_read_file(FILE *);
#endif