Create file streams

This commit is contained in:
Wilson Lin 2018-07-04 23:25:38 +12:00
parent 66c6e53eed
commit 3c484d5c84
3 changed files with 81 additions and 0 deletions

37
src/main/c/util/fstream.h Normal file
View File

@ -0,0 +1,37 @@
#ifndef _HDR_HYPERBUILD_UTIL_FSTREAM
#define _HDR_HYPERBUILD_UTIL_FSTREAM
#include <errno.h>
#include <stdio.h>
#include "../error/error.c"
#define HBU_FSTREAM_BUILD_INFRA(type, mode, noun, verb) \
typedef struct hbu_fstream##type##_s { \
const char *name; \
FILE *fd; \
} *hbu_fstream##type##_t; \
\
hbu_fstream##type##_t hbu_fstream##type##_create(char *path) { \
hbu_fstream##type##_t fstream = malloc(sizeof(struct hbu_fstream##type##_s)); \
fstream->name = path; \
\
FILE *fd = fopen(path, mode); \
\
if (fd == NULL) { \
hbe_fatal("Failed to open file %s for " verb, fstream->name); \
} \
\
fstream->fd = fd; \
\
return fstream; \
} \
\
void hbu_fstream##type##_delete(hbu_fstream##type##_t fstream) { \
if (fclose(fstream->fd) == EOF) { \
hbe_fatal("Failed to close " noun " stream for file %s", fstream->name); \
} \
\
free(fstream); \
}
#endif // _HDR_HYPERBUILD_UTIL_FSTREAM

View File

@ -0,0 +1,27 @@
#ifndef _HDR_HYPERBUILD_UTIL_FSTREAMIN
#define _HDR_HYPERBUILD_UTIL_FSTREAMIN
#include <errno.h>
#include <stdio.h>
#include "hbchar.h"
#include "../error/error.c"
#include "fstream.h"
HBU_FSTREAM_BUILD_INFRA(in, "r", "read", "reading")
hb_eod_char_t hbu_fstreamin_read(hbu_fstreamin_t fstreamin) {
hb_char_t c;
if (fread(&c, SIZEOF_CHAR, 1, fstreamin->fd) != SIZEOF_CHAR) {
if (ferror(fstreamin->fd)) {
hbe_fatal("Failed to read input file %s", fstreamin->name);
}
// Must be EOF
return HB_EOD;
}
return c;
}
#endif // _HDR_HYPERBUILD_UTIL_FSTREAMIN

View File

@ -0,0 +1,17 @@
#ifndef _HDR_HYPERBUILD_UTIL_FSTREAMOUT
#define _HDR_HYPERBUILD_UTIL_FSTREAMOUT
#include <errno.h>
#include <stdio.h>
#include "../error/error.c"
#include "fstream.h"
HBU_FSTREAM_BUILD_INFRA(out, "w", "write", "writing")
void hbu_fstreamout_write(hbu_fstreamout_t fstreamout, hb_char_t c) {
if (fwrite(&c, SIZEOF_CHAR, 1, fstreamout->fd) != SIZEOF_CHAR) {
hbe_fatal("Failed to write to output file %s", fstreamout->name);
}
}
#endif // _HDR_HYPERBUILD_UTIL_FSTREAMOUT