Main Page   Class Hierarchy   Alphabetical List   Data Structures   File List   Data Fields   Globals  

getinput.c

Go to the documentation of this file.
00001 /*
00002   getinput.c
00003 
00004   Non-blocking input on stdin
00005 
00006 
00007 Modifications:
00008 
00009 21-Sep-1999 WPS ifdef'd out CE stuff.
00010 
00011   */
00012 
00013 #ifdef WIN32
00014 
00015 #ifdef UNDER_CE
00016 
00017 // This is currently  impossible to implement in CE.
00018 int getinput(char *buffer, int maxchars)
00019 {
00020  return -1;
00021 }
00022 
00023 #else
00024 // WIN32 but not CE, ( ie. Windows 95,98,2000, or NT)
00025 
00026 #include <stdio.h>
00027 #include <string.h>
00028 
00029 /*
00030   getinput() blocks on stdin, returning number of chars read, -1
00031   if EOF.
00032   */
00033 int getinput(char *buffer, int maxchars)
00034 {
00035   if (NULL == fgets(buffer, maxchars, stdin))
00036     {
00037       if (feof(stdin))
00038         {
00039           return 0;
00040         }
00041 
00042       return -1;
00043     }
00044 
00045   return strlen(buffer);
00046 }
00047 
00048 #endif
00049 
00050 #else
00051 
00052 #include <unistd.h>             /* STDIN_FILENO */
00053 #include <fcntl.h>              /* F_GETFL, O_NONBLOCK */
00054 
00055 /*
00056   getinput() returns the number of chars read, -1 if no chars were available,
00057   or 0 if EOF. It doesn't block, so you can call this repeatedly and when
00058   it returns non-zero you have that many chars, not including the added NULL.
00059   */
00060 int getinput(char *buffer, int maxchars)
00061 {
00062   int flags;
00063   int nchars;
00064   int index = 0;
00065 
00066   /* save the flags */
00067   flags = fcntl(STDIN_FILENO, F_GETFL);
00068 
00069   /* make terminal non-blocking */
00070   fcntl(STDIN_FILENO, F_SETFL, O_NONBLOCK);
00071 
00072   /* read the outstanding chars, one by one, until newline or no more */
00073   while (1 == (nchars = read(STDIN_FILENO, &buffer[index], 1)))
00074     {
00075       if (buffer[index++] == '\n')
00076         {
00077           buffer[index] = 0;    /* null terminate */
00078           break;
00079         }
00080     }
00081 
00082   /* restore the terminal */
00083   fcntl(STDIN_FILENO, F_SETFL, flags);
00084 
00085   if (nchars == -1)
00086     {
00087       return -1;                /* nothing new */
00088     }
00089 
00090   if (nchars == 0)
00091     {
00092       return 0;                 /* end of file */
00093     }
00094 
00095   return index;
00096 }
00097 
00098 #endif /* not WIN32 */

Generated on Sun Dec 2 15:27:40 2001 for EMC by doxygen1.2.11.1 written by Dimitri van Heesch, © 1997-2001