From Newsgroup: comp.lang.tcl
Am 20.06.24 um 12:16 schrieb Mark Summerfield:
I have an app that reads config info from a .ini file.
But the first time the app is run there is no .ini file exits.
Below is the code I'm using to ensure that the .ini file is closed if
opened; but surely there's a better way?
I really want to get rid of the first if command
if {![file isfile $::config::filename]} {
return
}
try {
set fh [::ini::open $::config::filename -encoding utf-8 r]
set ::config::geometry \
[::ini::value $fh Window geometry [wm geometry .]]
tk scaling [::ini::value $fh Window scale [tk scaling]]
ttk::style theme use \
[::ini::value $fh Window theme [ttk::style theme use]]
set ::config::tab [::ini::value $fh Window tab]
} finally {
if {[info exists fh] && $fh ne ""} {
::ini::close $fh
}
}
Hello,
use trap with try
a example:
# tclWinError.c
proc writeFileWithHandling {filename data} {
try {
# r+ the file must already exist.
# generates an error if the file does not exist
set fd [open $filename r+]
puts $fd $data
puts "Data was successfully written to the file."
} trap {POSIX EISDIR} {} {
puts "Error POSIX EISDIR: It is a directory, not a file."
} trap {POSIX ENOENT} {} {
puts "Error POSIX ENOENT: The file does not exist."
} trap {} {} {
puts "Error {}: an unknown error occurred."
} finally {
if {[info exists fd]} {
close $fd
# Ensure the file is closed
}
}
}
# without puts
proc writeFile {filename data} {
try {
# r+ the file must already exist.
# generates an error if the file does not exist
set fd [open $filename r+]
puts $fd $data
puts "Data was successfully written to the file."
} trap {} {} {
} finally {
if {[info exists fd]} {
close $fd
# Ensure the file is closed
}
}
}
# example.txt exists in the directory
# example2.txt does not exist in the directory
# Example function calls
writeFileWithHandling "example.txt" "New data line"
writeFileWithHandling "example2.txt" "New data line"
puts "Output:"
puts $::errorInfo
puts \n
#without puts
writeFile "example.txt" "New data line"
writeFile "example2.txt" "New data line"
#Gregor
--- Synchronet 3.20a-Linux NewsLink 1.114