0

i was reading about streams and found out that we could control streams by using setvbuf() function...it was written tat in line buffered mode stream sends the data to the file when a newline is encountered and in unbuffered there is no buffering...so i wrote the following code...

#include<stdio.h>


int main()
{

setvbuf(stdin, NULL, _IONBF, 40);
setvbuf(stdout, NULL, _IONBF, 40);
while(1)
{
char a[40];
int n;
n=fread(a, 1, 4, stdin);

if(n>0)
fwrite(a, 1, n, stdout);
}
return 0;
}

so i think that because these are unbuffered streams, input should be sent to stdout as soon as i write to the screen...but the program waited for me to press enter after writing each line and then only output appeared on the screen(as a result of fwrite)...my question is why the progam waited for enter(i.e. newline) when these were unbuffered streams...

AvinashK
  • 3,309
  • 8
  • 43
  • 94

1 Answers1

1

I believe this is due to how the shell in your environment works: the data you entered is not available on stdin until you hit enter, so the fread is blocking until it can read something from the stream

Think how you would need to handle back-space and the like if the shell passed every character to the buffer

Attila
  • 28,265
  • 3
  • 46
  • 55
  • @attila...but theoretically typed in characters should be passed to file immediately...isn't it? – AvinashK Jun 20 '12 at 19:43
  • @avinash - what file are you talking about? `stdin` behaves as if it was a file (for the purposes of various function calls), but it is _not_ a file. Also, I do not know of an environment where it would be advantageous to pass the typed-in characters to the standard input immediately (talking about direct user interaction) – Attila Jun 20 '12 at 20:11
  • @attila...here i am calling anything represented by a filestream as a file...and also i am not talking about advantage...i am just asking if that is what it does – AvinashK Jun 21 '12 at 15:16
  • @avinash - as I mentioned, it depends on the shell (which shits in between the user and `stdin` of the program), and I am not aware of a shell that will pass on characters as you type them (but it is certainly possible). If you want to do that, you will have to look at libraries that provide that level of interaction (using lower-level OS calls), like the _ncurses_ library – Attila Jun 21 '12 at 15:22