Skip to content

Instantly share code, notes, and snippets.

@aptavout aptavout/getch.c
Last active Aug 29, 2015

Embed
What would you like to do?
One implementation of getchar()
#include <stdio.h>
#define MAXLINE 81 /* MAXLINE = MAXCARD + 1 */
#define MAXCARD 80
#define NEWLINE '\n'
#define BLANK ' '
static int getch_lastc = MAXLINE;
static char getch_buf[MAXLINE];
int getch(char *c);
int readlin(char buf[]);
main()
{
char c;
while (getch(&c) != EOF) {
putchar(c);
}
}
int getch(char *c)
{
extern char getch_buf[];
int eof_signal;
extern int getch_lastc;
getch_lastc = getch_lastc + 1;
if (getch_lastc >= MAXLINE) {
eof_signal = readlin(getch_buf);
getch_lastc = 0;
}
if (eof_signal == EOF) {
*c = 0;
return EOF;
} else {
*c = getch_buf[getch_lastc];
if (*c == NEWLINE)
getch_lastc = MAXLINE;
return *c;
}
}
int readlin(char buf[])
{
int i;
int c;
for (i=0; i<MAXLINE-1 && ((c = getchar())!=EOF) && c!=NEWLINE; ++i) {
buf[i] = c;
}
if (c == NEWLINE)
buf[i++] = NEWLINE;
buf[i] = '\0';
if (c == EOF)
return EOF;
return 0; /* not EOF */
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.