简体   繁体   中英

TCL ( import a file and want to read line by line )

I want to read line by line values in cd.txt and consider each value as variable.

# Damper Properties
set Kd 0.000001;

set Cd [open "CD.txt" r];

set ad 0.000001;

if [catch {open $CD.txt r} cd] { ; # Open the input file and check for error

  puts stderr "Cannot open $inFilename for reading"; # output error statement

} else {

  foreach line [[read $cd] \n] { ; # Look at each line in the file

    if {[llength $line] == 0} { ; # Blank line -> do nothing

      continue;

    } else {

      set Xvalues $line; # execute operation on read data

    }

  }

  close $cd; ; # Close the input file

}

# Define ViscousDamper Material

#uniaxialMaterial ViscousDamper $matTag $Kd $Cd $alpha

uniaxialMaterial ViscousDamper     1   $Kd  $Cd $ad

Whats wrong in it? Values in cd.txt is a decimal value. The loop is not working. Please help.

This line:

foreach line [[read $cd] \n] { ; # Look at each line in the file

is missing a critical bit. This version looks more correct:

foreach line [split [read $cd] \n] { ; # Look at each line in the file

(I hope you're really doing more than just setting Xvalues to each non-empty line, since that's unlikely to be useful by itself.)

You're opening the wrong file:

set Cd [open "CD.txt" r];

The Cd variable now holds a file handle, and the value is something like "file3421". You then do

if [catch {open $CD.txt r} cd] { ; # Open the input file and check for error

You're now trying to open the file "file3421.txt" -- I'd expect you to get an "file not found" error there.

Also, you should brace the expression:

if {[catch {open "CD.txt" r} cd]} { ...
#..^............................^ 

The idiomatic way to read lines from a file is:

while {[gets $cd line] != -1} { ...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM