user2669068
user2669068

Reputation: 185

How to avoid newline at the end of written file

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

Answers (4)

Donal Fellows
Donal Fellows

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

potrzebie
potrzebie

Reputation: 1798

If you already have all the lines in memory:

puts -nonewline $file [join $lines \n]

Upvotes: 4

mrjl
mrjl

Reputation: 56

what about this?

puts -nonewline $file "\n$line"

Upvotes: 0

mrjl
mrjl

Reputation: 56

maybe:

puts -nonewline $file $line

Upvotes: 1

Related Questions