PDA

View Full Version : use of read write


usha
01-21-2006, 06:22 AM
hi
here i am writing u a code to read from key board(stdin) and write on the screen(stdout).

main()
{
char ch;
printf("enter a character ");
read(0,&ch,1);
write(1,&ch,1);
}

now there is no problem in execution. but i have doubt in execution. when i dont give any \n
in the printf statement at the end then first read is getting executed and then printf.if i give \n then printf is executed first then read.
why does this happen
pls give clarification
thanks in advance
usha

RobSeace
01-21-2006, 05:25 PM
Because you're using stdio, and by default there is buffering on stdin and stdout
(at least if they're associated with a tty)... You can force the output by doing
"fflush(stdout);" after the printf()... Or, you could fprintf() to stderr instead, which
is never buffered... Or, you could use write() instead of printf(), since you appear
to be using read() and write() to do the other input/output... It's always a bad idea
to mix stdio I/O with raw read()/write()-style I/O; you should pick one or the other
and stick with it...