Originally Posted by
Subsonics
I'm not sure I follow, "record" as a name is abstract enough to be any record, but unlike arrays have the nice feature of named members. When ever I would actually use this struct I could call the instance something like addressbook_record.
That doesn't work: what are you going to name the members? I notice that in your examples, you name them stuff like artist, soing, duration, year... those have nothing to do with a generic CSV record. If you want to do that, then you might as well couple CSV parsing with your subject domain addressbook_record, because this "abstract enough to be any record" isn't.
In other words, if you want the coupling, do something like this:
Code:
struct song_record {
char *artist;
char *song;
unsigned int duration;
unsigned int year;
};
void song_record_read_from_csv(struct song_record *record, FILE *fp)
{
/* read a line (i.e., CSV record) from the file
* parse the line into CSV fields
* populate artist and song using field[0] and field[1]
* convert field[2] and field[3] to unsigned int and use the result to
* populate duration and year respectively.
*/
}
Hence, if you have an addressbook_record, you would define song_record_read_from_csv to parse a CSV record from file into your addressbook_record.
But if you want to decouple, do something like this:
Code:
struct csv_record {
char **fields;
};
struct csv_file {
csv_record *records;
size_t num_records;
size_t num_fields;
};
struct song_record {
char *artist;
char *song;
unsigned int duration;
unsigned int year;
};
void parse_csv_file(csv_file *file, FILE *fp)
{
/* ... */
}
void song_record_read_from_csv(struct song_record *record, csv_record *csv)
{
/* populate artist and song using csv->fields[0] and csv->fields[1]
* convert csv->fields[2] and csv->fields[3] to unsigned int and use the
* result to populate duration and year respectively.
*/
}
Hence, if you have an addressbook_record, you only need to define addressbook_record_read_from_csv to take the fields of the CSV record to populate your addressbook_record. You do not need to rewrite any CSV file parsing since it is decoupled from your subject domain struct.
EDIT:
Originally Posted by
anduril462
Since data field you store is just a string, I don't see you really gaining much benefit by having an actual struct versus a char **.
Indeed. struct record is just a sham when it cannot decide whether it is a CSV record or a song record, and is really just an array of strings.