From ae16685996bc761302697aad1e3e67be1e7124b7 Mon Sep 17 00:00:00 2001 From: Michael Ossmann Date: Thu, 21 Feb 2013 13:46:22 -0700 Subject: [PATCH] improved error handling --- host/libhackrf/examples/hackrf_spiflash.c | 61 ++++++++++++++--------- 1 file changed, 37 insertions(+), 24 deletions(-) diff --git a/host/libhackrf/examples/hackrf_spiflash.c b/host/libhackrf/examples/hackrf_spiflash.c index ba856628..d32124c0 100644 --- a/host/libhackrf/examples/hackrf_spiflash.c +++ b/host/libhackrf/examples/hackrf_spiflash.c @@ -146,6 +146,17 @@ int main(int argc, char** argv) return EXIT_FAILURE; } + if (read) { + fd = fopen(path, "wb"); + } else { + fd = fopen(path, "rb"); + } + + if (fd == NULL) { + fprintf(stderr, "Failed to open file: %s\n", path); + return EXIT_FAILURE; + } + result = hackrf_init(); if (result != HACKRF_SUCCESS) { fprintf(stderr, "hackrf_init() failed: %s (%d)\n", @@ -160,47 +171,49 @@ int main(int argc, char** argv) return EXIT_FAILURE; } - if (read) { - fd = fopen(path, "wb"); - } else { - fd = fopen(path, "rb"); - } - - if (fd == NULL) { - fprintf(stderr, "Failed to open file: %s\n", path); - return EXIT_FAILURE; - } - if (read) { result = hackrf_spiflash_read(device, address, length, data); - if (result == HACKRF_SUCCESS) { - const ssize_t bytes_written = fwrite(data, 1, length, fd); - if (bytes_written != length) { - fprintf(stderr, "Failed write to file (wrote %d bytes).\n", - (int)bytes_written); - fclose(fd); - fd = NULL; - return EXIT_FAILURE; - } + if (result != HACKRF_SUCCESS) { + fprintf(stderr, "hackrf_spiflash_read() failed: %s (%d)\n", + hackrf_error_name(result), result); + fclose(fd); + fd = NULL; + return EXIT_FAILURE; + } + const ssize_t bytes_written = fwrite(data, 1, length, fd); + if (bytes_written != length) { + fprintf(stderr, "Failed write to file (wrote %d bytes).\n", + (int)bytes_written); + fclose(fd); + fd = NULL; + return EXIT_FAILURE; } } else { const ssize_t bytes_read = fread(data, 1, length, fd); - if (bytes_read == length) { - result = hackrf_spiflash_write(device, address, length, data); - } else { + if (bytes_read != length) { fprintf(stderr, "Failed read file (read %d bytes).\n", (int)bytes_read); fclose(fd); fd = NULL; return EXIT_FAILURE; } + result = hackrf_spiflash_write(device, address, length, data); + if (result != HACKRF_SUCCESS) { + fprintf(stderr, "hackrf_spiflash_write() failed: %s (%d)\n", + hackrf_error_name(result), result); + fclose(fd); + fd = NULL; + return EXIT_FAILURE; + } } result = hackrf_close(device); if (result != HACKRF_SUCCESS) { fprintf(stderr, "hackrf_close() failed: %s (%d)\n", hackrf_error_name(result), result); - return -1; + fclose(fd); + fd = NULL; + return EXIT_FAILURE; } hackrf_exit();