Skip to content

Commit 2cd40ae

Browse files
authored
Add File Input Output in Tcl (#5056)
1 parent 4a86544 commit 2cd40ae

File tree

1 file changed

+54
-0
lines changed

1 file changed

+54
-0
lines changed
Lines changed: 54 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,54 @@
1+
#!/usr/bin/env tclsh
2+
3+
proc writeToFile {filename} {
4+
if {[catch {set fh [open $filename w]} err]} {
5+
puts "Error opening file for writing \"$filename\": $err"
6+
return 1
7+
}
8+
9+
if {[catch {
10+
puts $fh "A line of text"
11+
puts $fh "Another line of text"
12+
flush $fh
13+
} err]} {
14+
puts "Error writing to file \"$filename\": $err"
15+
close $fh
16+
return 1
17+
}
18+
19+
close $fh
20+
return 0
21+
}
22+
23+
proc readFromFile {filename} {
24+
if {[catch {set fh [open $filename r]} err]} {
25+
puts "Error reading from file \"$filename\": $err"
26+
return 1
27+
}
28+
29+
set linesRead 0
30+
if {[catch {
31+
while {[gets $fh line] >= 0} {
32+
puts $line
33+
incr linesRead
34+
}
35+
} err]} {
36+
puts "Error reading from file \"$filename\": $err"
37+
close $fh
38+
return 1
39+
}
40+
41+
if {$linesRead == 0} {
42+
puts "(File \"$filename\" is empty)"
43+
}
44+
45+
close $fh
46+
return 0
47+
}
48+
49+
set filename "output.txt"
50+
if {[ writeToFile $filename] != 0} { exit 1 }
51+
if {[readFromFile $filename] != 0} { exit 1 }
52+
53+
exit 0
54+

0 commit comments

Comments
 (0)