Reputation: 185
is there a way in tcl to avoid having the newline at the end of a written file ?
puts $file $line
Thanks.
Upvotes: 2
Views: 12592
Reputation: 137787
First off, puts
always writes the last argument you give, followed by a newline unless you also specified the -nonewline
option.
When writing lines in a loop, where you don't want a newline at the end of just the last line, you're really using \n
as a line separator rather than a line terminator. To do that without building all the data in a single string, it is easiest to use an extra variable to hold the separator and have that start out empty.
# Initially
set separator ""
# Inside the loop
puts -nonewline $file $separator$line
set separator "\n"
Setting a (hopefully local) variable to a constant value is a small amount of extra work to do per iteration, and it is easy to be sure that this does the right thing.
(Of course, if you were really writing to a file you could also use seek
or chan truncate
after the loop to make things patched up. It's harder to do though — “newline” isn't always written as a single byte, depending on the fconfigure -translation
option — and doesn't work with non-file channels at all. Not recommended in this case!)
Upvotes: 11
Reputation: 1798
If you already have all the lines in memory:
puts -nonewline $file [join $lines \n]
Upvotes: 4