Search code examples
tclflushputs

Use of flush in TCL


I was working through TCL in an interactive manner. I wrote something like :

puts -nonewline "Enter file you want to read : "
# flush stdout
gets stdin fileName

# TCL statements follow...

When flush was commented , the puts message was not getting printed while on un-commenting it , script was executing further. I read a question about same issue here : [https://stackoverflow.com/questions/19002619/tcl-usage-of-flush-command][1]

But I have same question which the user asked in comment there which is :

puts directs its output to stdout while gets looks for input from stdin. Then why we need to use flush in the first place itself ? If i do something like :

puts -nonewline "message1 ,,"
puts -nonewline "message2 ,"
puts "message 3."

I wouldn't require any flush statements here , then why in the previous example ?

Please help me to understand this. Thanks


Solution

  • By default, when a channel is opened to write to the console or terminal, it is put into line buffering mode so that only complete lines are written (that is, a flush is done whenever a write ends with a newline; puts adds one if not told not to do so). This is usually the right thing, but not when writing prompts such as you're doing. (When a channel is opened to anything else, it starts out fully buffered; that makes things faster for bulk data operations.) The only exception to this is stderr, which is always unbuffered by default; that's because we want to make sure that anything written when the program fails actually makes it out (as stderr is for diagnostic info).

    You can change the buffering of a channel with chan configure or fconfigure (depending on Tcl version). This can be highly advisable in some situations, such as when working with line-oriented network protocols. Or you can flush explicitly when needed.

    Tcl flushes channels when you close them.

    Flushing has exactly no impact on reading from a channel.