From a2b4fe1466c167cec93757cee4d80129f93ee963 Mon Sep 17 00:00:00 2001 From: Peter Evans Date: Sun, 31 Dec 2017 20:28:11 -0600 Subject: [PATCH] Write an fread function for segments; use in apple2.dd --- include/vm_segment.h | 1 + src/apple2.dd.c | 9 +++++++-- src/vm_segment.c | 22 ++++++++++++++++++++++ 3 files changed, 30 insertions(+), 2 deletions(-) diff --git a/include/vm_segment.h b/include/vm_segment.h index 39ee838..c2655a0 100644 --- a/include/vm_segment.h +++ b/include/vm_segment.h @@ -54,6 +54,7 @@ struct vm_segment { }; extern int vm_segment_copy(vm_segment *, vm_segment *, size_t, size_t, size_t); +extern int vm_segment_fread(vm_segment *, FILE *, size_t); extern int vm_segment_read_map(vm_segment *, size_t, vm_segment_read_fn); extern int vm_segment_set(vm_segment *, size_t, vm_8bit); extern int vm_segment_write_map(vm_segment *, size_t, vm_segment_write_fn); diff --git a/src/apple2.dd.c b/src/apple2.dd.c index 52a5cee..bc51ce1 100644 --- a/src/apple2.dd.c +++ b/src/apple2.dd.c @@ -33,6 +33,7 @@ int apple2dd_insert(apple2dd *drive, FILE *stream) { struct stat finfo; + int err; if (stream == NULL) { log_critical("File stream is null"); @@ -57,8 +58,12 @@ apple2dd_insert(apple2dd *drive, FILE *stream) drive->track_pos = 0; drive->sector_pos = 0; - // FIXME: vm_segment code should be doing this - fread(drive->data->memory, sizeof(vm_8bit), finfo.st_size, stream); + // Read the data from the stream and write into the memory segment + err = vm_segment_fread(drive->data, stream, finfo.st_size); + if (err != OK) { + log_critical("Could not read data into disk drive"); + return err; + } return OK; } diff --git a/src/vm_segment.c b/src/vm_segment.c index c02e03e..9f0c473 100644 --- a/src/vm_segment.c +++ b/src/vm_segment.c @@ -204,3 +204,25 @@ vm_segment_write_map(vm_segment *segment, segment->write_table[addr] = fn; return OK; } + +/* + * Read the given file stream and write the contents into the given + * segment, up to len bytes. If we could not read from the file stream + * for some reason, signal that and return an error. + */ +int +vm_segment_fread(vm_segment *segment, FILE *stream, size_t len) +{ + fread(segment->memory, sizeof(vm_8bit), len, stream); + + // fread() may return zero in the case of an error, but it may + // return a positive non-zero number short of len; we can't quite + // count on just that to tell us something went wrong (especially if + // len was not a valid length for the file to begin with). + if (ferror(stream)) { + log_critical("Could not read file stream: %s\n", strerror(errno)); + return ERR_BADFILE; + } + + return OK; +}