Reputation: 43
I'm having some troubles deleting the contents of a text file. From what I can tell, I cannot seem to rename or delete this file and create a new one with the same name, due to permission issues with the PLM software we use. Unfortunately, I am on my own here, since no one seems to know what exactly is wrong.
I can read and write to this file, however. So I've been looking at the seek command and doing something like this:
set f [open "C:/John/myFile.txt" "a+"]
seek $f 0
set fp [tell $f]
seek $f 0 end
set end [tell $f]
# Restore current file pointer
seek $f $fp
while { $fp < $end } {
puts -nonewline $f " "
incr fp
}
close $f
This seems to replace all the lines with spaces, but I'm not sure this is the correct way to approach this. Can someone give me some pointers? I'm still relatively new to Tcl.
Thanks!
Upvotes: 0
Views: 7466
Reputation: 137787
If you've got at least Tcl 8.5, open the file in r+
or w+
mode (experimentation may be required) and then use chan truncate
:
chan truncate $f 0
If you're using 8.4 or before, you have instead to do this (and it only works for truncating to empty):
close [open $thefilename "w"]
(The w
mode creates the file if it doesn't exist, and truncates it to empty on open if it does. The rest of the program might or might not like this!)
Note however that this does not reset where other channels open on the file think they are. This can lead to strange effects (such as writing at a large offset, with the OS filling out the preceding bytes with zeroes) even without locking.
Upvotes: 6
Reputation: 5375
A really easy way to do this is to just over-write your file with an empty file. For example create an empty file (you can do this manually or using the following TCL code):
set blank_file [open "C:/tmp/blank.txt" "w"]
close $blank_file
Then just over-write your original file with the blank file as follows:
file rename -force "C:/tmp/blank.txt" "C:/John/myFile.txt"
Of course, you may have permissions problems if something else has grabbed the file.
Upvotes: 1
Reputation: 15192
close [open $path w]
And voila, an empty file. If this file does not yet exist, it will be created.
Upvotes: 3
Reputation: 1062
You say the file is opened exclusively with another process but you can write to it ?! I think you have permission problems. Are you using Linux or Unix ?! (It seems it is a Windows system but permission problems usually occur on Linux/Unix systems, It is weird, isn't it ?!)
The file is not exclusively opened if you are able to read and write to it and you may have no appropriate permission to delete the file.
Also it is better to test the code on a file you know you have all permissions on it. If the code is working you can focus on your target file. Also you can Google for 'how to file operations in Tcl'. Read this Manipulating Files With Tcl
Upvotes: 0