> I reduced the buffer size to 1..And it worked pretty good
You're lucky it worked at all
char buf[1];
fgets(buf, 2, stdin)
That extra byte which fgets will write is going into the great unknown.
> let's say i typed "a" and didn't press enter
Until you press enter, the text is being buffered by the operating system (and/or the C library). When you press enter, the text is chopped up into sizeof(buff)-1 blocks and returned to your code in successive calls to fgets()
> so where is the typed matter going all this time ? into the memory ?
Yes - output files are also buffered
If you want to see data in your file immediately, then use fflush()
> but when there's no fclose(fp) in the program, how come it saved
A well behaved C runtime will close all open files when you exit the program normally. If on the other hand your program were to crash at this time, you would probably lose.
Code:
#include <stdio.h>
int main ( void ) {
char buff[5];
FILE *fp;
fp = fopen( "test.txt", "w" );
if ( fp == NULL ) {
perror( "Unable to open" );
return 1;
}
while ( fgets( buff, sizeof(buff), stdin ) != NULL ) {
printf( "Processing line `%s`\n", buff );
fputs( buff, fp );
fflush( fp ); // if you really want to see each fputs in the file
}
fclose( fp ); // close the file
clearerr( stdin ); // clear the EOF state on stdin
return 0;
}
And this is what it looks like when you run the code
Code:
the quick brown fox jumps over the lazy dog
Processing line `the `
Processing line `quic`
Processing line `k br`
Processing line `own `
Processing line `fox `
Processing line `jump`
Processing line `s ov`
Processing line `er t`
Processing line `he l`
Processing line `azy `
Processing line `dog
`
a man a plan a canal panama
Processing line `a ma`
Processing line `n a `
Processing line `plan`
Processing line ` a c`
Processing line `anal`
Processing line ` pan`
Processing line `ama
`
^Z