FREE Subscription to Dr. Dobb’s Digest: Same Great Content, New Digital Edition
Site Archive (Complete)
Open Source
Email
Print
Reprint

add to:
Del.icio.us
Digg
Google
Furl
Slashdot
Y! MyWeb
Blink
October 10, 2009
C Snippet #7

Bob Stout
Querying in a .BAT file, using a timeout default

Q: HOW DO I... ask questions in a .BAT file, then use a timeout default?

A: This Snippet originally (last updated in 1997) addressed a DOS operational issue rather than C coding issues, but was offered for its demonstration value. This new version updates the original, providing additional options and bullet-proofing. It has been tested under both DOS, Win32, and POSIX (UNIX, Linux) systems. The syntax of this utility is:

QUERY prompt arg time

prompt, arg, and time represent required (they were originally optional) argument fields.

  • prompt is the phrase or question to display.

  • arg can be any of either Y', 'N', 'y', 'n', 'T', 'F', 't', or 'f'. and is the default answer.
  • time is how long, in seconds, to wait for a response before using the default. If "0" is entered, no timeout will occur.

The answers may be either Y(es)/N(o) or T(rue)/F(alse). Case is insignificant. The utility formats a query string using the prompt and the default. The displayed options will be either "y/n" or "t/f" with the default response character capitalized. If the choices are "y/n", the "t/f" responses are ignored. Likewise, if the choices are "t/f", the "y/n" responses are ignored. If the user gives a "Y" answer or if the default answer is "Y", the program returns a DOS ERRORLEVEL of 1. If the user gives a "T" answer or if the default answer is "T", the program returns a DOS ERRORLEVEL of 1. In all other cases, it returns an ERRORLEVEL of 0. Useful C coding hints are provided for handling command-line arguments, using the clock() function, and returning ERRORLEVELs from your programs.


/* ** QUERY.C - Timed query with default for batch files ** ** Usage: QUERY prompt_string X n ** where: prompt_string = query question ** X = Default answer, `Y', `N', 'T', 'F' 'y', 'n', 't' or 'f' ** n = Seconds to wait before using default answer, ** 0 for no timeout ** ** Notes: 1. All options are required. ** 2. If the #include <stdio.h> #include <time.h> #include <ctype.h> #include <stdlib.h> #include <string.h> #include <conio.h> #include "sniptype.h"

void usage(void) { puts("Usage: QUERY prompt_string X n"); puts(" where: prompt_String = query quesation"); puts(" X = Default answer, `Y', `N', 'T', 'F' 'y', 'n', 't' or 'f'"); puts(" n = Seconds to wait before using default answer,"); puts(" 0 for no timeout"); puts("Notes: 1. All options are required."); puts(" 2. If the <Enter> key is pressed, the default response is returned."); puts(" 3. If the deafult is 'Y', 'N', 'y', or 'n', the response must match."); puts(" 4. If the deafult is 'T', 'F', 't', or 'f', the response must match."); puts(" 5. 'Y', 'y', 'T, or 't' answers return 1."); puts(" 6. 'N', 'n', 'F, or 'f' answers return 0."); }

main(int argc, char *argv[]) { int ch = -1, def_ch = -1; char *prompt = "(y/n) ", options[] = "YNTF"; clock_t start, limit = (clock_t)0; Boolean_T done = False_;

// Sanity check the arguments if (argc < 4 || !strchr("YNTFyntf", *argv[2])) { usage(); return (int)Error_; }

// Display the query question fputs(argv[1], stderr); fputc(' ', stderr);

def_ch = toupper(*argv[2]);

// Got the default, now build and display the prompt string if (strchr("YT", def_ch)) { prompt[1] = def_ch; if ('Y' == def_ch) prompt[3] = 'n'; else prompt[3] = 'f'; } else if (strchr("NF", def_ch)) { prompt[3] = def_ch; if ('N' == def_ch) prompt[1] = 'y'; else prompt[1] = 't'; } fputs(prompt, stderr);

// Start timing start = clock(); limit = (clock_t)(CLK_TCK * atoi(argv[3]));

// Wait for a keypress or a timeout while (!done && !strchr(options, ch)) { while (!done && !kbhit()) { if (limit) { if (limit < (clock() - start)) { // Timed out, use the default ch = def_ch; done = True_; break; } } else done = False_; }

if (done) break;

// Validate the response switch (ch = toupper(getch())) { case '\r': // Handle CR, LF defaults case '\n': ch = def_ch; done = True_; break;

case 'Y': // Check for a valid response case 'N': case 'T': case 'F': if ((strchr("YN", ch) && strchr("YN", def_ch)) || (strchr("TF", ch) && strchr("TF", def_ch))) { done = True_; break; } // Incompatible answers, fall through to...

default: // Invalid repsonse, try again ch = -1; break; } };

// Display the response & return fputc(ch, stderr); fputc('\n', stderr); return (NULL != strchr("YT", ch)); }


/* ** SNIPTYPE.H - Include file for SNIPPETS data types and commonly used macros */

#ifndef SNIPTYPE__H #define SNIPTYPE__H

#include <stdlib.h> /* For free() */ #include <string.h> /* For NULL & strlen() */

typedef enum {Error_ = -1, Success_, False_ = 0, True_} Boolean_T;

#ifdef BYTE #undef BYTE #endif #ifdef WORD #undef WORD #endif # ifdef DWORD #undef DWORD #endif typedef unsigned char BYTE; typedef unsigned short WORD; typedef unsigned long DWORD;

typedef union { signed char c; BYTE b; } VAR8_;

typedef union { VAR8_ v8[2]; signed short s; WORD w; } VAR16_;

typedef union { VAR16_ v16[2]; signed long l; DWORD dw; float f; void *p; } VAR32_;

typedef union { VAR32_ v32[2]; double d; } VAR64_;

#define NUL '\0' #define LAST_CHAR(s) (((char *)s)[strlen(s) - 1]) #define TOBOOL(x) (!(!(x))) #define FREE(p) (free(p),(p)=NULL)

#endif /* SNIPTYPE__H */

More C Snippets

All the code in C Snippets is either public domain or freeware and may therefore freely be used by the C programming community without restrictions. In most cases, if the original author is someone other than myself he or she will be identified. Thanks to all who have contributed to this collection over the years. I hope Dr. Dobb's readers will find these useful.

TOP 5 ARTICLES
No Top Articles.



MICROSITES
FEATURED TOPIC

ADDITIONAL TOPICS

INFO-LINK