/* * binres.c * * Summary: Read or write a binary restart file. * * Author: David Hardy */ #include #include "binres.h" #include "mdtypes.h" #include "error.h" #undef START #define START 1 #undef VEC #define VEC 2 int binres_init(Binres *b) { /* init everything */ b->f = NULL; b->nelem = 0; b->elemsize = 0; b->access = 0; b->state = 0; b->status = 0; return 0; } void binres_destroy(Binres *b) { /* clear everything */ b->f = NULL; b->nelem = 0; b->elemsize = 0; b->access = 0; b->state = 0; b->status = 0; } int binres_open(Binres *b, const char *fname, int access, int type) { switch (type) { case MD_FVEC: b->elemsize = sizeof(MD_Fvec); break; case MD_DVEC: b->elemsize = sizeof(MD_Dvec); break; default: mdio_fatal("illegal type, file %s, line %d\n", __FILE__, __LINE__); } switch (access) { case BINRES_READ: b->f = fopen(fname, "rb"); break; case BINRES_WRITE: b->f = fopen(fname, "wb"); break; default: mdio_fatal("illegal access, file %s, line %d\n", __FILE__, __LINE__); } MDIO_ASSERT(b->f != NULL); b->access = access; b->state = START; return 0; } int binres_close(Binres *b) { int ret; ret = fclose(b->f); MDIO_ASSERT(ret == 0); return ret; } int binres_read(Binres *b, void *vec, int len, int *num, int *max) { int n; MDIO_ASSERT(b->access == BINRES_READ); switch (b->state) { case START: fread((void *) max, sizeof(int), 1, b->f); b->nelem = 0; b->state = VEC; /* fall through */ case VEC: n = *max - b->nelem; if (n > 0) { if (n > len) n = len; fread(vec, b->elemsize, n, b->f); b->nelem += n; } *num = n; break; default: mdio_fatal("illegal state, file %s, line %d\n", __FILE__, __LINE__); } return (b->nelem < *max); } int binres_write(Binres *b, const void *vec, int num, int max) { MDIO_ASSERT(b->access == BINRES_WRITE); switch (b->state) { case START: fwrite((void *) &max, sizeof(int), 1, b->f); b->nelem = 0; b->state = VEC; /* fall through */ case VEC: MDIO_ASSERT(b->nelem + num <= max); fwrite(vec, b->elemsize, num, b->f); b->nelem += num; break; default: mdio_fatal("illegal state, file %s, line %d\n", __FILE__, __LINE__); } return (b->nelem < max); }