📜  Tcl-文件I / O

📅  最后修改于: 2020-10-16 06:30:12             🧑  作者: Mango


Tcl借助内置命令open,read,puts,gets和close来支持文件处理。

文件表示字节序列,无论是文本文件还是二进制文件都没有关系。

开启档案

Tcl使用open命令在Tcl中打开文件。打开文件的语法如下-

open fileName accessMode

在这里, filename是字符串字面量,您将使用它来命名文件, accessMode可以具有以下值之一-

Sr.No. Mode & Description
1

r

Opens an existing text file for reading purpose and the file must exist. This is the default mode used when no accessMode is specified.

2

w

Opens a text file for writing, if it does not exist, then a new file is created else existing file is truncated.

3

a

Opens a text file for writing in appending mode and file must exist. Here, your program will start appending content in the existing file content.

4

r+

Opens a text file for reading and writing both. File must exist already.

5

w+

Opens a text file for reading and writing both. It first truncate the file to zero length if it exists otherwise create the file if it does not exist.

6

a+

Opens a text file for reading and writing both. It creates the file if it does not exist. The reading will start from the beginning, but writing can only be appended.

关闭档案

要关闭文件,请使用close命令。 close的语法如下-

close fileName 

当程序使用完该文件后,必须关闭该程序打开的所有文件。在大多数情况下,不需要显式关闭文件。当文件对象自动终止时,它们将自动关闭。

写文件

Puts命令用于写入打开的文件。

puts $filename "text to write"

下面显示了一个写入文件的简单示例。

#!/usr/bin/tclsh

set fp [open "input.txt" w+]
puts $fp "test"
close $fp

编译并执行上述代码后,它将在其下启动的目录(在程序的工作目录中)创建一个新文件input.txt

读取文件

以下是从文件读取的简单命令-

set file_data [read $fp]

读写的完整示例如下所示-

#!/usr/bin/tclsh

set fp [open "input.txt" w+]
puts $fp "test"
close $fp
set fp [open "input.txt" r]
set file_data [read $fp]
puts $file_data
close $fp

编译并执行上述代码后,它将读取上一部分中创建的文件,并产生以下结果-

test

这是另一个读取文件直到文件末尾的示例-

#!/usr/bin/tclsh

set fp [open "input.txt" w+]
puts $fp "test\ntest"
close $fp
set fp [open "input.txt" r]

while { [gets $fp data] >= 0 } {
   puts $data
}
close $fp

编译并执行上述代码后,它将读取上一部分中创建的文件,并产生以下结果-

test
test