Page 384 - Programming Microcontrollers in C
P. 384

Coding the Alpha Data     369

            Read data from the keyboard
                              A function get() is used to read data from a keyboard into a
                          data buffer. This function is used in the monitor. A problem with
                          many such functions is that they do not provide proper protection
                          from a buffer overflow as the data are read in. The standard library
                          function fgets() almost meets the needs of this function and more.
                          The “more” in this case is the reason that we should not use the
                          fgets() in this case. This function is part of the standard library
                          and as such, it requires the definition of an input. The most often
                          used input file here is the one named stdin. When we construct
                          this system, we do not want to include all of the side effects of adding
                          the standard library to our system. Therefore, in this case, it is probably
                          best to write the function get() from scratch.
                              The function get() is shown below. This function takes two
                          parameters. The first is a pointer to a character string where the input
                          data are to be stored and the second is the length of this array. In the
                          event that the input data size exceeds the array size, the data array is
                          filled with zeros. Otherwise, the new line character is placed on the
                          end of the string and the string is terminated with a null character.

                   void get(char* a,int n)
                   {
                       /* read in field and terminate the read with an ‘\n’ */
                       int i=0,c;


                       while((c=getchar())!=’\n’ && i<(n-1))
                          a[i++]=c;
                       if(i<n-1)
                       {
                          a[i++]=’\n’;
                          a[i]=’\0';
                       }
                       else  /* input did not terminate soon enough */
                          for(i=0;i<n;i++)
                                 a[i]=0;
                   }
                              Listing 7-9: get() Input Data Routine
   379   380   381   382   383   384   385   386   387   388   389