练习进行文件操作,包括打开文件、创建文件、读写文件等。
set path [pwd]/Desktop/FileIO/
set name "dont_touch.xdc"
set newName "dont_touch_new.xdc"
set optr "r"
set optw "w+"
set rdFile ""
set retval [eval catch {{set fdr [eval open [append rdFile $path $name] $optr]}} msg]
if { $retval != 0 } {
puts $msg
return
}
set wrFile ""
eval set fdw [eval open [append wrFile $path $newName] $optw]
if { [file exists $fdw] != 0 } {
puts hello!
}
set lineNum 1
while { [gets $fdr line] >= 0 } {
set newLine "$lineNum: "
append newLine $line
puts $fdw $newLine
incr lineNum
}
以上练习通过eval将不同的命令和参数组合在一起,然后执行。主要作用是将dont_touch.xdc中的文本读出,并且在每一行的开头添加行号,然后输出到另一个dont_touch_new.xdc文件。
其中name、newName、optr、optw等变量定义时也可以不写“”。
注意其中catch的用法,由于其语法要求,需要两对{}。
[eval open [append rdFile $path $name] $optr]也可以写成[eval open [append rdFile $path $name $optr]]。但是写成后者时,optr的定义就需要加上“”,并加上空格,写成:set optr " r"。因为append可以将多个字符串组合,如果optr定义时没有空格,那么作为option的r字符会被附加到前一个字符串的末尾,不再被看作是open的option。
file exists可以用于检测某个文件是否存在。
open附加option为r时,如果文件不存在,不会自动创建文件。而w、w+等option会自动创建文件。
open的访问权限选项如下:
r: Open the file for reading only; the file must already exist. This is the default value if access is not specified.
r+: Open the file for both reading and writing; the file must already exist.
w: Open the file for writing only. Truncate it if it exists. If it does not exist, create a new file.
w+: Open the file for reading and writing. Truncate it if it exists. If it does not exist, create a new file.
a: Open the file for writing only. If the file does not exist, create a new empty file. Set the file pointer to the end of the file prior to each write.
a+: Open the file for reading and writing. If the file does not exist, create a new empty file. Set the initial access position to the end of the file.