Debug This I: Solution

The solution to previous Debug This problem is that out stream is a buffered I/O. If out stream is stdout and if it is connected to terminal, the buffer size is 1024, else it is 4094, as per this post. So, whatever is written to out stream will only be flushed if one of the following two things happen: (a) If the buffer is full OR (b) If the buffer is explicitly flushed out.

In the given problem, input file had only 1098 characters. So, an explicit call to flush will resolve the issue.
 
#include <stdio.h> 

#define MAXBUF 100 

int main() 
{
    char *in  = "Sample.txt"; 
    char *out = "outFile.txt"; 
    char buf[MAXBUF]; 

    FILE  *rfs,  *wfs; 

    rfs = fopen(in, "r"); 
    /* error checking required */

    wfs = fopen(out, "w");
    /* error checking required */

    while(fgets(buf, MAXBUF, rfs)) 
    {   
        fputs(buf, wfs);
        fflush(wfs);    /* Flush the output buffer */
    }   

    fclose(rfs); 
    fclose(wfs); 

    return 0;  
}

On my box, I gradually increased the size of input file and noticed that at 8192 characters, the buffer gets full and out stream is flushed. If input 8192 < size < 16384, the behavior repeats. 

Labels: , , , , ,