| View previous topic :: View next topic |
| Author |
Message |
admiralboom Voice
Joined: 30 Oct 2009 Posts: 3
|
Posted: Fri Oct 30, 2009 11:59 am Post subject: I want to edit a line but clobbers the whole file |
|
|
I need a suggestion on appending a line in the file without clobbering the whold file, suggestions?
| Code: |
bind pub - !status proc_status
proc proc_status { ircnick userhost handle channel arg } {
set status "$arg"
if {$status == ""} {
puthelp "PRIVMSG $ircnick :Please supply your status"
return 0
}
set fs [open "/srv/httpd/htdocs/status.txt" r]
set tmpfs [open "/srv/httpd/htdocs/tmpstatus.txt" w]
set change 0
while {![eof $fs]} {
if {![gets $fs line]} {
puts -nonewline $tmpfs "$line\n"
} elseif {[lindex $line 1] == $ircnick} {
puts -nonewline $tmpfs "[unixtime] $ircnick $status\n"
set change 1
}
}
if {!$change} {
puts -nonewline $tmpfs "[unixtime] $ircnick $status"
puthelp "PRIVMSG $ircnick : Your status has been added."
} else {
puthelp "PRIVMSG $ircnick : Your status has been updated."
}
close $fs
close $tmpfs
set tmpfs [open "/srv/httpd/htdocs/tmpstatus.txt" r]
set statusdb "[read $tmpfs]"
close $tmpfs
set fs [open "/srv/httpd/htdocs/status.txt" w]
puts -nonewline $fs "$statusdb"
close $fs
return 0
}
|
|
|
| Back to top |
|
 |
tomekk Master

Joined: 28 Nov 2008 Posts: 255 Location: Oswiecim / Poland
|
|
| Back to top |
|
 |
admiralboom Voice
Joined: 30 Oct 2009 Posts: 3
|
Posted: Fri Oct 30, 2009 1:14 pm Post subject: |
|
|
| I suppose so although how do I tell it which line to edit? |
|
| Back to top |
|
 |
tomekk Master

Joined: 28 Nov 2008 Posts: 255 Location: Oswiecim / Poland
|
Posted: Fri Oct 30, 2009 1:31 pm Post subject: |
|
|
ahhh, my fault...
you can read whole file and later you can use some loop (for, foreach) to check the line
it will be smth like:
1. open file 'r', read whole content to some Var, close the file
2. open the same filem with 'w'
3. copy all from Var to this file (insert some IF inside loop, if line match - write it, if not - don't)
3. close the file
file.txt:
example.tcl:
| Code: | #!/usr/bin/tclsh
set read_data [open "file.txt" r]
set all_lines [split [read $read_data] "\n"]
close $read_data
set change "two"
set write_data [open "file.txt" w]
foreach file_line $all_lines {
if {$file_line != ""} {
if {$file_line == $change} {
puts $write_data "woohooo"
} {
puts $write_data $file_line
}
}
}
close $write_data
|
file.txt after:
Its possible to this with one 'file open' by using 'seek' and 'a+' mode.
Last edited by tomekk on Sat Oct 31, 2009 2:26 pm; edited 1 time in total |
|
| Back to top |
|
 |
Sir_Fz Revered One

Joined: 27 Apr 2003 Posts: 3793 Location: Lebanon
|
|
| Back to top |
|
 |
admiralboom Voice
Joined: 30 Oct 2009 Posts: 3
|
Posted: Sat Oct 31, 2009 9:52 am Post subject: |
|
|
| Thank you tomekk that did it. |
|
| Back to top |
|
 |
|