From 214abeb18154066b1aee6dcc3edd172ea679a654 Mon Sep 17 00:00:00 2001 From: Intel A80486DX2-66 Date: Mon, 23 Sep 2024 00:43:25 +0300 Subject: [PATCH] C: fix file I/O code --- src/template.c | 44 +++++++++++++++++++++++++++++++++++++++----- 1 file changed, 39 insertions(+), 5 deletions(-) diff --git a/src/template.c b/src/template.c index 19b6d3d..8237fa6 100644 --- a/src/template.c +++ b/src/template.c @@ -9,6 +9,38 @@ #include "`fwrite_le`" +#if _FILE_OFFSET_BITS == 64 || _POSIX_C_SOURCE >= 200112L + # define FSEEK_MACRO fseeko + # define FSEEK_FUNCTION_NAME "fseeko" +typedef off_t file_offset_t; +#else + # define FSEEK_MACRO fseek + # define FSEEK_FUNCTION_NAME "fseek" +typedef int file_offset_t; +#endif + +#define STRINGIZE(x) #x + +#define FILE_IO_NO_FAIL(function, ptr, size, nitems, stream) do { \ + if (function(ptr, size, nitems, stream) != nitems) { \ + /* clean up */ \ + free(buffer); \ + \ + perror(STRINGIZE(function)); \ + exit(EXIT_FAILURE); \ + } \ +} while (0) + +#define FSEEK_NO_FAIL(...) do { \ + if (FSEEK_MACRO(__VA_ARGS__) == -1) { \ + perror(FSEEK_FUNCTION_NAME); \ + exit(EXIT_FAILURE); \ + } \ +} while (0) + +#define FREAD_NO_FAIL(...) FILE_IO_NO_FAIL(fread, __VA_ARGS__) +#define FWRITE_NO_FAIL(...) FILE_IO_NO_FAIL(fwrite, __VA_ARGS__) + // typedefs typedef uintmax_t bb_counter_t; typedef long double bb_fp_return_t; @@ -418,7 +450,7 @@ main(void) for (size_t counter = 0; counter < REPEAT_TIMES; counter++) { # if SEQUENTIAL_MODE - off_t position_read = header_size; + file_offset_t position_read = header_size; calc_block_size = BLOCK_SIZE; for (size_t seq = 0, time = 0; seq < MAX; seq++, time += BLOCK_SIZE) { @@ -428,10 +460,12 @@ main(void) end = true; } - fseeko(output_file, position_read, SEEK_SET); - fread(buffer, sizeof(SAMPLE_TYPE), calc_block_size, output_file); - fseeko(output_file, 0, SEEK_END); - fwrite(buffer, sizeof(SAMPLE_TYPE), calc_block_size, output_file); + FSEEK_NO_FAIL(output_file, position_read, SEEK_SET); + FREAD_NO_FAIL(buffer, sizeof(SAMPLE_TYPE), calc_block_size, + output_file); + FSEEK_NO_FAIL(output_file, 0, SEEK_END); + FWRITE_NO_FAIL(buffer, sizeof(SAMPLE_TYPE), calc_block_size, + output_file); if (end) break;