Wednesday, 16 November 2011

Why don’t I see my screen output until the program ends? in C programming

Why don’t I see my screen output until the program ends?

Sometimes, depending on the compiler and operating system you are working on, output will be buffered. “Buffered” means that any output you send to a device, whether the screen, the disk, or the printer, is saved until there is a large enough amount to be written efficiently. When enough output has been saved, it is written to the device as one block.

This process can cause two problems for the programmer unaware of its effects. First,output might not be displayed on-screen until sometime after your program sends it. This effect might be a problem if the programmer is trying to keep track of exactly what his program is doing, and when. The second, and more insidious, problem can occur when your program prints some prompt for the userand waits for input. There is no guarantee in the ANSI C standard that attempting to get input from the user will flush the output buffer. Therefore, the message you sent to the screen might not be displayed before your program tries to get input. The user thus does not know that he is being prompted for input; as far as he can tell, your lovely program has just suddenly stopped working.How can this problem be fixed? There are two ways. The first way to fix the problem is to insert the line
setvbuf( stdout , NULL , _IONBF , 0 );
at the start of the program, before any output has been printed. This code has the effect of completely unbuffering output to the screen. After this command is executed, every character that is sent to the screen is printed immediately as it is sent.

This method is a convenient way to solve the problem, but it is not ideal. Without getting into a technical discussion of screen input and output, I’ll just state that there are good reasons why screen output is buffered, and that you might want to leave it so.

This brings us to the other way of solving the output-buffering problem. The command fflush(), when
invoked on an output buffer, causes it to empty itself even if it is not full. Therefore, to solve the screen
buffering problem, you can simply insert the command
fflush( stdout );
whenever you want the output buffer to be flushed. It would be appropriate to flush the output buffer before requesting input from the user, or before the program goes into an extensive computation that will delay it for a time. This way, whenever the program pauses, you’ll know why.

Cross Reference:

None.

No comments:

Post a Comment