File Input Output in Tcl

Published on 08 October 2025 (Updated: 08 October 2025)

Welcome to the File Input Output in Tcl page! Here, you'll find the source code for this program as well as a description of how the program works.

Current Solution

#!/usr/bin/env tclsh

proc writeToFile {filename} {
    if {[catch {set fh [open $filename w]} err]} {
        puts "Error opening file for writing \"$filename\": $err"
        return 1
    }

    if {[catch {
        puts $fh "A line of text"
        puts $fh "Another line of text"
        flush $fh
    } err]} {
        puts "Error writing to file \"$filename\": $err"
        close $fh
        return 1
    }

    close $fh
    return 0
}

proc readFromFile {filename} {
    if {[catch {set fh [open $filename r]} err]} {
        puts "Error reading from file \"$filename\": $err"
        return 1
    }

    set linesRead 0
    if {[catch {
        while {[gets $fh line] >= 0} {
            puts $line
            incr linesRead
        }
    } err]} {
        puts "Error reading from file \"$filename\": $err"
        close $fh
        return 1
    }

    if {$linesRead == 0} {
        puts "(File \"$filename\" is empty)"
    }

    close $fh
    return 0
}

set filename "output.txt"
if {[ writeToFile $filename] != 0} { exit 1 }
if {[readFromFile $filename] != 0} { exit 1 }

exit 0


File Input Output in Tcl was written by:

If you see anything you'd like to change or update, please consider contributing.

How to Implement the Solution

No 'How to Implement the Solution' section available. Please consider contributing.

How to Run the Solution

No 'How to Run the Solution' section available. Please consider contributing.