Dr. Dobb's is part of the Informa Tech Division of Informa PLC

This site is operated by a business or businesses owned by Informa PLC and all copyright resides with them. Informa PLC's registered office is 5 Howick Place, London SW1P 1WG. Registered in England and Wales. Number 8860726.

Channels ▼


C Snippet #7

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]))
            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_;
                  else  done = False_;

            if (done)

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

            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_;
                  // Incompatible answers, fall through to...

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

      // 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
#ifdef WORD
 #undef WORD
#  ifdef DWORD
 #undef DWORD
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.

Related Reading

More Insights

Currently we allow the following HTML tags in comments:

Single tags

These tags can be used alone and don't need an ending tag.

<br> Defines a single line break

<hr> Defines a horizontal line

Matching tags

These require an ending tag - e.g. <i>italic text</i>

<a> Defines an anchor

<b> Defines bold text

<big> Defines big text

<blockquote> Defines a long quotation

<caption> Defines a table caption

<cite> Defines a citation

<code> Defines computer code text

<em> Defines emphasized text

<fieldset> Defines a border around elements in a form

<h1> This is heading 1

<h2> This is heading 2

<h3> This is heading 3

<h4> This is heading 4

<h5> This is heading 5

<h6> This is heading 6

<i> Defines italic text

<p> Defines a paragraph

<pre> Defines preformatted text

<q> Defines a short quotation

<samp> Defines sample computer code text

<small> Defines small text

<span> Defines a section in a document

<s> Defines strikethrough text

<strike> Defines strikethrough text

<strong> Defines strong text

<sub> Defines subscripted text

<sup> Defines superscripted text

<u> Defines underlined text

Dr. Dobb's encourages readers to engage in spirited, healthy debate, including taking us to task. However, Dr. Dobb's moderates all comments posted to our site, and reserves the right to modify or remove any content that it determines to be derogatory, offensive, inflammatory, vulgar, irrelevant/off-topic, racist or obvious marketing or spam. Dr. Dobb's further reserves the right to disable the profile of any commenter participating in said activities.

Disqus Tips To upload an avatar photo, first complete your Disqus profile. | View the list of supported HTML tags you can use to style comments. | Please read our commenting policy.