title: Buffered reading from stdin using fread in C
body: <p>I am trying to efficiently read from the <code>stdin</code> by using <code>setvbuf</code> in `_IOFBF~ mode. I am new to buffering. I am looking for <em>working</em> examples.</p>
  
  <p>The input begins with two integers (<code>n</code>,<code>k</code>). The next <code>n</code> lines of input contain 1 integer. The aim is to print how many integers are divisible by <code>k</code>.</p>
  
  <pre><code>#define BUFSIZE 32
  int main(){
    int n, k, tmp, ans=0, i, j;
    char buf[BUFSIZE+1] = {'0'};
    setvbuf(stdin, (char*)NULL, _IONBF, 0);
    scanf("%d%d\n", &amp;n, &amp;k);
    while(n&gt;0 &amp;&amp; fread(buf, (size_t)1, (size_t)BUFSIZE, stdin)){
      i=0; j=0;
      while(n&gt;0 &amp;&amp; sscanf(buf+j, "%d%n", &amp;tmp, &amp;i)){
      //printf("tmp %d - scan %d\n",tmp,i); //for debugging
        if(tmp%k==0)  ++ans;
        j += i; //increment the position where sscanf should read from
        --n;
      }
    }
    printf("%d", ans);
    return 0;
  }
  </code></pre>
  
  <p>The problem is if number is at the boundary, the <em>buffer</em> <code>buf</code> will read <code>23</code> from <code>2354\n</code>, when it should have either read <code>2354</code> (which it cannot) or nothing at all.</p>
  
  <p>How can I solve this issue?</p>
  
  <hr>
  
  <p>Edit<br>
  <a href="https://stackoverflow.com/questions/2371292/buffered-reading-from-stdin-using-fread-in-c/2378520#2378520">Resolved now (with analysis)</a>.</p>
  
  <p>Edit<br>
  <a href="http://www.spoj.pl/problems/INTEST/" rel="nofollow noreferrer">Complete Problem Specification</a></p>