문제

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...

도움이 되었습니까?

해결책

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

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top