// SPDX-License-Identifier: GPL-3.0-or-later #include #include #include #include #include /* Split a writable record such as MARS|RED,COLD|4. Each cursor belongs to one scan. The tokens point directly into the line read from disk. */ static int showRecord(char *line) { char *fields, *traits, *end; char summary[112]; char *name = strtok_r(line, "|", &fields); char *list = strtok_r(NULL, "|", &fields); if (!name || !list) return 0; char *first = strtok_r(list, ",", &traits); char *second = strtok_r(NULL, ",", &traits); if (!first || !second || strtok_r(NULL, ",", &traits)) return 0; /* Resume the outer scan exactly where we left it. */ char *text = strtok_r(NULL, "|", &fields); if (!text || strtok_r(NULL, "|", &fields) || !isdigit((unsigned char)*text)) return 0; errno = 0; unsigned long orbit = strtoul(text, &end, 10); if (*end || errno == ERANGE || orbit < 1UL || orbit > 8UL) return 0; int length = snprintf(summary, sizeof(summary), "SURVEY: %s\nTRAITS: %s AND %s\nORBIT FROM SUN: %lu", name, first, second, orbit); if (length < 0 || length >= (int)sizeof(summary)) return 0; printf("%s\n", summary); return 1; } int main(void) { char line[64], choice; unsigned record = 0; int tooLong = 0; cls(1); printf("PLANET SURVEY\n1 EARTH 2 MARS\n"); do choice = waitkey(0); while (choice != '1' && choice != '2'); FILE *log = fopen("PLANETS.TXT", "r"); if (!log) { printf("CANNOT OPEN PLANETS.TXT\n"); return 1; } /* Skip the flight notes. The first data line is Earth, the second Mars. */ while (fgets(line, sizeof(line), log)) { unsigned length = strcspn(line, "\n"); if (length == sizeof(line) - 1) { tooLong = 1; // Never mistake part of a long line for a new record. break; } line[length] = '\0'; if (!line[0] || line[0] == '#') continue; if (++record == (unsigned)(choice - '0')) break; } /* An error can end a read loop just as end-of-file can. */ int diskError = ferror(log); if (fclose(log) == EOF || diskError) printf("DISK READ ERROR\n"); else if (tooLong) printf("SURVEY LINE TOO LONG\n"); else if (record != (unsigned)(choice - '0')) printf("NO MATCHING SURVEY RECORD\n"); else if (!showRecord(line)) printf("INVALID SURVEY RECORD\n"); else { printf("SURVEY COMPLETE\n"); return 0; } return 1; }