diff --git a/programs/fileio.c b/programs/fileio.c index c4737372a..9eb35fa8f 100644 --- a/programs/fileio.c +++ b/programs/fileio.c @@ -605,16 +605,10 @@ FIO_openDstFile(FIO_prefs_t* const prefs, dstFileName); return NULL; } - DISPLAY("zstd: %s already exists; overwrite (y/N) ? ", - dstFileName); - { int ch = getchar(); - if ((ch!='Y') && (ch!='y')) { - DISPLAY(" not overwritten \n"); - return NULL; - } - /* flush rest of input line */ - while ((ch!=EOF) && (ch!='\n')) ch = getchar(); - } } + DISPLAY("zstd: %s already exists; ", dstFileName); + if (UTIL_requireUserConfirmationToProceed("overwrite (y/n) ? ", "Not overwritten \n", "yY")) + return NULL; + } /* need to unlink */ FIO_removeFile(dstFileName); } } @@ -1683,19 +1677,8 @@ int FIO_compressMultipleFilenames(FIO_prefs_t* const prefs, } else { DISPLAY("zstd: WARNING: all input files will be processed and concatenated into a single output file: %s ", outFileName); } - if (prefs->removeSrcFile) { - DISPLAY("Proceed? (y/n): "); - { - int ch = getchar(); - if ((ch != 'y') && (ch != 'Y')) { - DISPLAY("zstd: aborting...\n"); - return 1; - } - /* flush the rest */ - while ((ch!=EOF) && (ch!='\n')) - ch = getchar(); - } - } + if (prefs->removeSrcFile) + error = UTIL_requireUserConfirmationToProceed("Proceed? (y/n): ", "Aborting...", "yY"); DISPLAY("\n"); } ress.dstFile = FIO_openDstFile(prefs, NULL, outFileName); diff --git a/programs/util.c b/programs/util.c index fc88ab35c..6b220f39a 100644 --- a/programs/util.c +++ b/programs/util.c @@ -87,6 +87,22 @@ UTIL_STATIC void* UTIL_realloc(void *ptr, size_t size) ******************************************/ int g_utilDisplayLevel; +int UTIL_requireUserConfirmationToProceed(const char* prompt, const char* abortMsg, + const char* acceptableLetters) { + int ch; + UTIL_DISPLAY("%s", prompt); + ch = getchar(); + if (strchr(acceptableLetters, ch) == NULL) { + UTIL_DISPLAY("%s", abortMsg); + return 1; + } + /* flush the rest */ + while ((ch!=EOF) && (ch!='\n')) + ch = getchar(); + + return 0; +} + /*-************************************* * Constants diff --git a/programs/util.h b/programs/util.h index f8eee86ad..aa48fd47a 100644 --- a/programs/util.h +++ b/programs/util.h @@ -93,6 +93,12 @@ extern "C" { ******************************************/ extern int g_utilDisplayLevel; +/** + * Displays a message prompt and returns success (0) if first character from stdin + * matches any from acceptableLetters. Otherwise, returns failure (1) and displays abortMsg. + */ +int UTIL_requireUserConfirmationToProceed(const char* const prompt, const char* const abortMsg, const char* const acceptableLetters); + /*-**************************************** * File functions