Easiest modification here then, would probably to use list operations..
The approach, roughly put, is to open the file as read-only, and read the whole content. Then use
split to convert the raw data into a list.
Once we've got a list, we can use commands such as
lappend/
linsert and
lrange to manipulate the list to suit our needs.
When we're satisfied with our new list, we then use
join to restore it to "raw data", and write it back to our file (which now has been opened as write-only).
A rough example:
Code: Select all
set fd [open thefile "RDONLY"]
set tmp [split [read -nonewline $fd] "\n"]
# Read the data, and split it on newlines...
close $fd
set fd [open thefile "WRONLY CREAT TRUNC"]
# Re-open the file in write-only mode, creating the file if it's missing, and clearing any previous content.
puts $fd [join [lrange [linsert $tmp 0 $data] 0 9] "\n"]
# Insert $data at the beginning of the list, then trim the list to the first 10 items, and finally join it back into a textstring, separating each list item with a newline. Write it back into (the empty) file.
close $fd
I've stacked a few steps of the process here, hope you get the picture anyway.
Edit: fixed minor bummer... Thank you papillon for pointing it out.