#include #include "rec_io.h" struct rec_io { char input[MAX_RECORD_LENGTH]; char * fields[MAX_RECORD_LENGTH/2 + 1]; char separator[MAX_SEPARATOR_LENGTH]; unsigned int separator_length; unsigned int fields_count; }; struct rec_io * rec_io_new() { struct rec_io * this = malloc(sizeof(struct rec_io)); if (this) { this->separator[0] = ' '; this->separator_length = 1; this->fields_count = 0; } return this; } void rec_io_destroy(struct rec_io * this) { free (this); } void rec_io_set_separator(struct rec_io * this, const char * begin, const char * end) { int i; for(i = 0; i < MAX_SEPARATOR_LENGTH && begin != end; ++i, ++begin) this->separator[i] = *begin; this->separator_length = i; } static int check_separator(const char * begin, const char * end, const char * sep_begin, const char * sep_end) { if (end - begin < sep_end - sep_begin) return 0; while (sep_begin != sep_end) { if (*sep_begin != *begin) return 0; ++begin; ++sep_begin; } return 1; } int rec_io_read_record(struct rec_io * this, const char * begin, const char * end) { this->fields_count = 0; char * input_p = this->input; const char * c = begin; while (c != end) { if (check_separator(c, end, this->separator, this->separator + this->separator_length)) { this->fields[this->fields_count] = input_p; c += this->separator_length; this->fields_count += 1; } else { *input_p++ = *c++; } } this->fields[this->fields_count] = input_p; this->fields_count += 1; return this->fields_count; } size_t rec_io_write_record(struct rec_io * this, char * out, size_t maxlen, const char * format) { size_t i = 0; while (*format != 0 && i < maxlen) { if (*format == '%') { unsigned int n = 0; for (++format; *format >= '0' and *format <= '9'; ++format) n = n * 10 + *format - '0'; if (n < this->fields_count) { /* ... */ } } else { out[i++] = *format++; } } return i; }