user1558482
user1558482

Reputation: 1

read and writing in tcl

Is there any way to read while it is writing at the same time in TCL?
I tried to use w + so and it didn't work.

set f0 [open out11.tr w+]  

So I want to read every line that has been done writing at the same time

Upvotes: 0

Views: 337

Answers (2)

Hai Vu
Hai Vu

Reputation: 40723

The following example opens a file with w+ (means read/write, but truncate the contents if file already exists). It then writes each line, and read back, write, then read back, ...

set lines {
    {Lorem ipsum dolor sit amet, consectetur adipiscing elit. Morbi}
    {accumsan est ut ante ornare et porta sem iaculis. Fusce a dolor}
    {magna, eget viverra quam. In sem justo, hendrerit a porttitor sit}
    {amet, scelerisque eu turpis. Nulla arcu arcu, condimentum vel}
    {fermentum sit amet, vulputate et sapien. Aenean convallis, purus vel}
    {molestie vehicula, diam eros adipiscing nibh, in dapibus nisi orci}
    {ut nisl. Ut fermentum felis a lectus lacinia dapibus. Nunc cursus}
    {nunc vitae massa fermentum imperdiet. In eu lectus quis arcu}
    {convallis imperdiet in quis tortor.}
}

set f [open out.txt w+]
set lastRead 0
foreach line $lines {
    # Write to the file
    puts $f $line

    # Read it back and display to stdout
    seek $f $lastRead
    gets $f line2
    set lastRead [tell $f]
}
close $f

Upvotes: 1

Donal Fellows
Donal Fellows

Reputation: 137577

While the w+ mode will work, it does truncate the file when you open it (because it's a modification of the w mode which does the same thing). If you don't want to wipe the existing data, use r+ instead (in which case the file must exist first).

When you want to create the file if it doesn't exist, be able to read and write it through the same channel, and don't want to truncate it on open, you have to use the other form of mode descriptor (derived from POSIX descriptors, if you're interested in mnemonics):

set f0 [open out11.tr {RDWR CREAT}]

(w+ is RDWR CREAT TRUNC, r+ is plain RDWR.)

Upvotes: 1

Related Questions