I'm making a script that requires writing, reading and deleting entries from a file. With the help of http://wiki.tcl.tk/367, I was able to make the bot write to a file and read it. However, I don't know how to delete a certain entry.
But... what you can do, is read the whole file into memory, and manipulate the content there. Then you either remove the old file and create a new (empty) one, or reopen the file with the TRUNC option (truncates, clears, the file). Finally, you then write your altered data there.
Rough example illustrating the process. No actual modification of the data is done here, and no assumptions as to the layout of the data are made.
set fid [open "myfile" "RDONLY"]
set data [read $fid]
close $fid
#manipulate $data
set fid [open "myfile" "WRONLY CREAT TRUNC"]
puts $fid $data
close $fid
I tend to prefer to keep a complete copy of a file's contents in memory and write it whenever a change is made. Perhaps something like the following code :-
# call this proc to read the file whatever.txt
proc pReadFile {} {
global vFileData
if {[file exists whatever.txt]} {
set id [open whatever.txt r]
set vFileData [split [read -nonewline $id] \n]
close $id
} else {
# handle file doesn't exist
}
return 0
}
# call this proc to write the file whatever.txt
# the file is first created if it doesn't exist or truncated if it does
proc pWriteFile {} {
global vFileData
if {[info exists vFileData]} {
set id [open whatever.txt w]
puts $id [join $vFileData \n]
close $id
} else {
# handle no data
}
return 0
}
# call this proc with 1 argument (text to search for in vFileData and if found remove that list item)
# only the first list item matching *txt* will be removed
# this proc calls pWriteFile if a deletion was made
proc pDeleteLine {txt} {
global vFileData
if {[info exists vFileData]} {
if {[set idx [lsearch $vFileData *$txt*]] != -1} {
set vFileData [lreplace $vFileData $idx $idx]
pWriteFile
} else {
# handle not found
}
} else {
# handle no data
}
return 0
}
# call this proc with 1 argument (text to add as a list item to vFileData)
# this proc calls pWriteFile after the text is appended as a list item
proc pAddLine {txt} {
global vFileData
lappend vFileData $txt
pWriteFile
return 0
}
Workable, as long as the data isn't a monstrous size.
http://wiki.tcl.tk/17396 Would be a good place to start, however, if you look in the TCL FAQ part of the forum. There is a thread dedicated to File stuff