How would you guys consider dealing with this?
Problem:
1.Open a random file in a directory.
2.Seek to a random point in the selected file.
3.Read from file till a certain char is found or eof.
4.If char is found: read and print to stdout till matching
char is found on the 'other end' of the text block.
My code is here, I'm interested in a more concise
approach:
Yes, it is a barebones win fortune script.
Problem:
1.Open a random file in a directory.
2.Seek to a random point in the selected file.
3.Read from file till a certain char is found or eof.
4.If char is found: read and print to stdout till matching
char is found on the 'other end' of the text block.
My code is here, I'm interested in a more concise
approach:
Code:
set dir [expr {$argc > 0 ? [lindex $argv 0] : "c:/fortune"}]
set debug 0
proc randFile {dir} {
set m 0
set contents [glob $dir/*]
foreach name $contents {if {[file isfile $name]} {incr m}}
if {$m > 0} {set key [expr int(1 + rand() * $m)]}
return [expr {[string length [lindex $contents $key]] > 0 ? [lindex $contents $key] : [randFile $dir]}]
}
proc fortunePrint {filename {tm "55000"}} {
global debug dir
set flag 0
if {![catch {set fd [open $filename r]} err_open]} {
set sz [file size $filename]
seek $fd [expr int(1 + rand() * $sz)] start
puts "\n\n\n#################FORTUNE##################\n"
while {1} {
set char [read $fd 1]
if {[eof $fd]} {break;}
if {$debug > 0} {puts -nonewline stdout $char}
if {"$char" == "%" && $flag < 1} {set flag 1; set char [read $fd 1]}
if {"$char" == "%" && $flag > 0} {set flag 0;break}
if {$flag > 0} {puts -nonewline stdout $char;flush stdout}
}
puts "\n###########################################"
close $fd
after $tm; return [fortunePrint [randFile $dir] $tm]
} else {
puts "ERROR: $err_open"
return -1
}
}
fortunePrint [randFile $dir]
Yes, it is a barebones win fortune script.