#include #include #include #include int validatePassportRecord(char *record) { static const int parsingKey = 1; static const int parsingValue = 2; int state = parsingKey; char key[BUFSIZ]; char value[BUFSIZ]; key[0] = '\0'; value[0] = '\0'; int i = 0; int fieldsFound = 0; int hasCID = 0; while ( *record != '\0' ) { assert(i < BUFSIZ); char c = *record; if ( state == parsingKey ) { if ( c == '\n' ) { ++record; continue; } if ( c == ':' ) { state = parsingValue; key[i] = '\0'; i = 0; } else { key[i] = c; ++i; } } else if ( state == parsingValue ) { if ( c == '\n' || c == ' ' ) { state = parsingKey; value[i] = '\0'; i = 0; ++fieldsFound; if ( strcmp(key, "cid") == 0 ) { hasCID = 1; } } else { value[i] = c; ++i; } } ++record; } return (fieldsFound == 8 || (fieldsFound == 7 && hasCID == 0)); } char *readPassportRecord(FILE *fp) { char *out = calloc(1, BUFSIZ); char *p = out; while ( fgets(p, BUFSIZ, fp) != NULL ) { if ( strlen(p) == 1 ) { // End of record break; } p += strlen(p); } if ( strlen(out) == 0 ) { free(out); out = NULL; } return out; } int main(int argc, const char * argv[]) { FILE *fp = fopen("input.txt", "r"); assert(fp != NULL); char *passportRecord; int validCount = 0; while ( (passportRecord = readPassportRecord(fp)) != NULL ) { int valid = validatePassportRecord(passportRecord); if ( valid ) { ++validCount; } free(passportRecord); } printf("validCount %d\n", validCount); fclose(fp); return 0; }