Explain this example C code

This code comes from K & R. I read it several times, but it still seems to me that I don't understand.

#define BUFSIZE 100

char buf[BUFSIZE];
int bufp = 0;

int getch(void)
{
      return(bufp>0)?buf[--bufp]:getchar();
}

int ungetch(int c)
{
      if(bufp>=BUFSIZE)
            printf("too many characters");
      else buf[bufp++]=c;
}

The purpose of these two functions, so K & R says, is to prevent the program from reading too much input. that is, without this code, the function may not be able to determine that it read enough data without first reading. But I do not understand how this works.

For example, consider getch (). As far as I can see, these are the steps that need to be completed:

  • check that bufp is greater than 0.
  • if so, return the value char buf [- bufp].
  • else return getchar ().

I would like to ask a more specific question, but I literally don’t know how this code achieves what it is intended to achieve, so my question is: what is (a) the purpose and (b) the reasoning for this code

Thanks in advance.

. K & R . 79 ( , )

+5
5

(a) - , " " , , ( 100 " " ). .

(b) getch buf, , bufp>0. buf , getchar. , buf : .

ungetch buf , , .

+9

" ", .

, getch, , ungetch . , .

+1

, , . , . , abcde12xy789, abcde, 12, xy, 789 (.. ), , , . , : , , , ; "" . ungetch: , , , ungetch. getch, , , .

+1
< > 1. , , - getch() ungetch().
  • 2. , , , , ?

. , . getchar(), , .

0

, . ( ) , ( ).

, ( ), () ( , ).

Due to the LIFO (Last in first out) stack property, the buffer in this code should be quene, since it will work better in case of more than one additional input.

This error in the code confused me, and finally, this buffer should be changed, as shown below.

#define BUFSIZE 100

char buf[BUFSIZE];
int bufr = 0;
int buff = 0;

int getch(void)
{
      if (bufr ==BUFSIZE)
             bufr=0;

      return(bufr>=0)?buf[bufr++]:getchar();
}

int ungetch(int c)
{
      if(buff>=BUFSIZE && bufr == 0)
            printf("too many characters");
      else if(buff ==BUFSIZE) 
            buff=0;  

       if(buff<=BUFSIZE)
            buf[buff++]=c;
}
0
source

All Articles