B09 Lab week 6

This lab is an exercise on binary I/O (fread, fwrite).

A struct “point” is defined in point.h; here it is again:

typedef struct point {
  int x, y;
} point;

Your job is to implement the following functions for writing and reading an array of these points to/from a file, given pathname and how many points:

ssize_t save_point_array(const char *pathname, size_t n, const point *a);
ssize_t load_point_array(const char *pathname, size_t n, point *a);

n is how many points to write/read, a is the address of the array of points. You may assume that the array has space for n elements.

Put your code in saveload.c (template provided among starter files).

More requirements on save_point_array

The fopen mode should be "w" or "wb". If opening fails, your return value is -1. You may print an error message to stderr for your sake, it's up to you.

If opening succeeds, your return value is how many points have been successfully written. (If you use fwrite correctly, it is simply fwrite's return value.)

Close the file before returning (if opening succeeded).

For simplicity, there is no need to handle other kinds of errors (apart from failure to open).

More requirements on load_point_array

The fopen mode should be "r" or "rb". If opening fails, your return value is -1. You may print an error message to stderr for your sake, it's up to you.

If opening succeeds, your return value is how many points have been successfully read. (If you use fread correctly, it is simply fread's return value.) It is possible that the file contains fewer or more than n points, so just read n points or what's available if fewer.

Close the file before returning (if opening succeeded).

For simplicity, there is no need to handle other kinds of errors (apart from failure to open).

Provided sample

A rudimentary test driver basictest.c and a sample file points-sample of 3 points are provided. You can compile and run basictest.c by:

gcc -O2 -Wall basictest.c saveload.c -o basictest
./basictest

When it tests save_point_array, it writes to points-saved.

When it tests load_point_array, it reads points-sample and compares with hardcoded expected values.

You can use the od program (doc) to visualize the files, e.g.,

od -t dI points-saved

which nicely formats the data as a sequence of ints.