// SPDX-License-Identifier: GPL-3.0-or-later #include #include #include #define CHECK(test) do { if (!(test)) { printf("FAIL LINE %u ERR %u\n", (unsigned)__LINE__, (unsigned)vcc_file_error()); return 1; } } while (0) static int writeArgs(FILE *stream, const char *format, ...) { va_list args; va_start(args, format); int result = vfprintf(stream, format, args); va_end(args); return result; } int formattedChecks(void) { FILE *stream = fopen("FORMAT.TXT", "w+b"); char expected[64], actual[64]; const char *format = "%%|%-6.3s|%04d|%.0u|%lo|%lX|%c|%lx"; int length = snprintf(expected, sizeof(expected), format, "MARS", -7, 0U, 0xFFFFFFFFUL, 0xDEADBEEFUL, 0, 0xABCUL); CHECK(stream && fprintf(stream, NULL) < 0 && ftell(stream) == 0L); CHECK(length > 0 && (unsigned) length < sizeof(expected)); CHECK(writeArgs(stream, format, "MARS", -7, 0U, 0xFFFFFFFFUL, 0xDEADBEEFUL, 0, 0xABCUL) == length); CHECK(fseek(stream, 0L, SEEK_SET) == 0 && fread(actual, 1, length, stream) == (unsigned) length); CHECK(!memcmp(expected, actual, length)); // A read with no EOF requires positioning, including for formatted writes. CHECK(fprintf(stream, "%s", "X") < 0 && vcc_file_error() == DECB_ERR_INVALID_ARGUMENT); CHECK(fseek(stream, 0L, SEEK_SET) == 0 && fprintf(stream, "%530s", "X") == 530); CHECK(fprintf(stream, "ABC%f") < 0); CHECK(fprintf(stream, "%32768d", 0) < 0 && ftell(stream) == 533L); CHECK(fseek(stream, 0L, SEEK_SET) == 0); for (unsigned i = 0; i < 529; ++i) CHECK(fgetc(stream) == ' '); CHECK(fgetc(stream) == 'X' && fgetc(stream) == 'A' && fgetc(stream) == 'B' && fgetc(stream) == 'C'); // A valid format can emit more bytes than a 16-bit int can report. CHECK(fseek(stream, 0L, SEEK_SET) == 0 && fprintf(stream, "%32767sX", "") < 0); CHECK(ftell(stream) == 32768L && fclose(stream) == 0); stream = fopen("FORMAT.TXT", "w"); CHECK(stream && fprintf(stream, "") == 0); CHECK(fprintf(stream, "%s %05u\n", "HELLO", 42U) == 12 && fclose(stream) == 0); stream = fopen("FORMAT.TXT", "r"); CHECK(stream && fprintf(stream, "") < 0 && vcc_file_error() == DECB_ERR_INVALID_ARGUMENT); CHECK(fclose(stream) == 0); return 0; } int formattedProtectedChecks(void) { // A short write can succeed in memory. A longer one reaches the // protected disk while formatting and reports the failure immediately. FILE *stream = fopen("SAFE.DAT", "r+b"); CHECK(stream && fprintf(stream, "%s", "X") == 1); CHECK(fprintf(stream, "%300s", "Y") < 0 && ferror(stream) == DECB_ERR_IO); CHECK(fprintf(stream, "") < 0 && fclose(stream) == EOF); return 0; }