exc/k&r/04-funcs-and-prog-struct/04-07.c

49 lines
886 B
C

#include <stdio.h>
#include <string.h>
#define MIN(A, B) ((A < B) ? (A) : (B))
/* -------- INPUT WITH PUSHBACK */
int _getchar()
{
extern int buffi;
extern char buffer[];
return buffi ? buffer[--buffi] : getchar();
}
#undef getchar
#define getchar() _getchar()
/* --------- MAIN PROGRAM */
#define SLEN 10
void ungets(char *s);
/* this program copies its input to its output,
* if ungets wokrks as expected */
int main()
{
int i, c;
char s[SLEN+1];
for (i = 0; i < SLEN && (c = getchar()) != EOF; i++)
s[i] = c;
s[i] = '\0';
ungets(s);
while ((c = getchar()) != EOF)
putchar(c);
}
#define BUFF_SIZE 100
int buffi;
char buffer[BUFF_SIZE];
/* ungets: pushes string s back to input */
void ungets(char *s)
{
int i = strlen(s);
for (i = MIN(i, BUFF_SIZE-buffi)-1; i >= 0; i--, buffi++)
buffer[buffi] = s[i];
}