TCL练习2:文件I/O

练习进行文件操作,包括打开文件、创建文件、读写文件等。

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.

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值