title: How to unit test c functions involving IO?
body: <p>I am facing problems in writing unit tests to C functions which involve IO operation. For example, below is the code I wrote to get an input string from the user from console. I do not know as to how to automate testing user input using getchar() function.</p>
  
  <pre><code>char * GetStringFromConsole()
  {
  
      char *strToReturn = NULL;
      int len = 128;
  
      strToReturn = (char*)malloc(len);
      if (strToReturn) 
      {
          int ch;
          char *ptr  = strToReturn;
          int counter = 0;
          for (; ;) 
          {
              ch = getchar();
              counter++;
  
              if (counter == len)
              {
                  strToReturn = realloc(strToReturn, len*=2 );
                  ptr = strToReturn + counter-1;
              }
  
              if ((ch != EOF) &amp;&amp; (ch != '\n') &amp;&amp; (counter &lt; len))
              {
                  *ptr++ = ch;
              }
              else 
              {
                  break;
              }
  
          }
          *ptr = '\0';
      }
      return strToReturn;
  }   
  </code></pre>