/** * myio.c - Declarations of simple I/O functions. * Based closely on code taken from section 4.3 of K&R. * Error checking removed because error messages should go to client, * not to user. */ // +---------+-------------------------------------------------------- // | Headers | // +---------+ #include // For getchar #include // For isdigit, isspace #include "myio.h" // +-----------+------------------------------------------------------ // | Constants | // +-----------+ /** * The maximum number of characters we can "unread". */ #define BUFSIZE 128 // +---------+-------------------------------------------------------- // | Globals | // +---------+ /** * The buffer in which we store unread characters. */ int buf[BUFSIZE]; /** * The position in the buffer that stores the most-recently unread * character. (When 0, there is no most-recently unread character.) */ int bufp = 0; // +--------------------+--------------------------------------------- // | Exported Functions | // +--------------------+ int getch () { return (bufp > 0) ? buf[--bufp] : getchar (); } // getch void ungetch (int c) { buf[bufp++] = c; } // ungetch int getint (int *pn) { int c; // The next input character int sign; // The sign of the integer read: Either +1 or -1. // Skip over whitespace while (isspace (c = getch ())) ; // Special case: EOF if (c == EOF) return c; // Make sure that we have a valid start to a number if ( (! isdigit (c)) && (c != '+') && (c != '-') ) { // We read too far. Step backwards ungetch (c); return 0; } // if it's not a number // Yay! It's a number. Get the sign. sign = (c == '-') ? -1 : 1; // Skip over the sign if ( (c == '+') || (c == '-') ) c = getch (); // Read the digits and convert to an integer. The general algorithm // should be familiar from atoi. *pn = 0; while (isdigit (c)) { *pn = 10 * *pn + (c - '0'); c = getch (); } // while // Incorporate the sign *pn *= sign; // We stopped because we read one character too far. Unget that // character. (We don't unget EOF because of a potential flaw in // the design of ungetch.) if (c != EOF) ungetch (c); // We return a special value for EOF if (c == EOF) return c; // And we're done return 1; } // getint