/* Program: READSTR.C Author : Kim Moser Date : 8 October, 1991 System : IBM PC / Borland Turbo C 2.0 Descrip: Reads string from console and echoes it. Useful for batch files which want user input. Usage : READSTR */ #include #include #include #include static void usage(void) { fputs("\ READSTR v1.0 10/08/1991 Copyright (C) 1991 Kim Moser All Rights Reserved\n\ Reads a string from the console and echoes it.\n\ \n\ usage: READSTR \n\ ", stderr ); exit(0); } #define EXTENDED 256 static int getkey(void); static int getkey(void) { int r; return (((r = getch()) != 0) ? r : getch()+EXTENDED); } static void readstr(char *s, int width); static void readstr(char *s, int width) { int i=0; int ch; while (1) { ch = getkey(); if (ch == '\b') { if (i) { fputs("\b \b", stderr); i--; } else { fputc('\a', stderr); } } else if (ch == 13) { break; } else { if (i < width) { s[i++] = ch; fputc(ch, stderr); } else { fputc('\a', stderr); } } } s[i] = '\0'; } void main(int argc, char **argv) { char *dest; int width; if (argc != 2) usage(); if ((width = atoi(argv[1])) <= 0) { usage(); } if ((dest = malloc(width+2)) == NULL) { fprintf(stderr, "malloc(%d) failed.\n", width); exit(-1); } readstr(dest, width); if (dest[strlen(dest)-1] == '\n') { dest[strlen(dest)-1] = '\0'; } fputs(dest, stdout); exit(0); }