I have several classes that are containers of various data that I read from / write to files. Usually the files have one entity per line (comma separated fields), but sometimes an entity is spread out among several lines.
I am trying to come up with a correct way of reusing the code reading and writing to a file. I could just have separate Read() and Write() functions in each class that deal with fstreams, all the checkings and strings formatting, but I feel like there should be a better way of reusing some code.
EDIT:
I realize I wasn’t specific enough about my problem. What stopped me from implementing it the way that some of the answers/comments have suggested, is that I have multi-line entities. So, I cannot just pass a line read from a file to a class to parse it. Some times I need to pass several lines.
When an entity is multi-line, usually it has an id field at the beginning of the line, so repeating ids mean that I need to read several lines.
For example, one file can be a polygon, then it’d have two coordinates per line, and this case is simple. But another file can be a set of polygons, then it’d have a polygon id plus two coordinates in each row. Like that:
id, x, y
0, 1, 2
0, 5, 0
0, -1, -1
1, 4, 4
1, 0, 8
1, -4, 4
1, 0, 0
EDIT 2:
While I was describing my problem in the first edit I realized what to do with my multi-line entities. I can still pass the read lines one by one to each class and make it populate unfinished entities. This seems obvious to me now, as always the problem becomes clear as soon as I try to explain it to others. Thanks for your comments!
If the data for the various containers is similar enough you should be able to make a single class for file IO. Pass it the type of object you want to write/populate.
Make each class implement an interface which defines two methods; one which takes the current line or an array of strings (after the line has been split) and sets all the objects values and another which returns a string with all the data as a comma separated string (this is for writing). The multi line situation will be more difficult to handle and it may be worth while to treat it as a special case.
The file IO class should only open/close, read/write, split lines on commas, and call methods on the object it’s passed. The file IO class should be passed pointer of the interfaces type.