RyanScottLewis
RyanScottLewis

Reputation: 14016

Outputting STDOUT To A File And Back Again

I routed STDOUT to a file using this code:

STDOUT.reopen(File.open("./OUTPUT",'w+'))

Now I need to route STDOUT to the terminal again.

How would I do this?

Upvotes: 8

Views: 7114

Answers (3)

Gee-Bee
Gee-Bee

Reputation: 3195

Even simpler if on UNIX:

STDOUT.reopen 'OUTPUT'
puts 'text to file'

STDOUT.reopen '/dev/tty'
puts 'text to console'

Upvotes: 1

khelll
khelll

Reputation: 23990

UPDATED

orig_std_out = STDOUT.clone
STDOUT.reopen(File.open('OUTPUT', 'w+'))
puts "test to file"
STDOUT.reopen(orig_std_out)
puts "test to screen"

Upvotes: 16

gavinb
gavinb

Reputation: 20018

You need to reopen STDOUT on file handle 1, which is the standard fd handle for stdout (0=stdin, 1=stdout, 2=stderr).

I'm not a Ruby guy, but I think this is about right:

STDOUT.reopen(IO.for_fd(1, "r"))

Upvotes: 2

Related Questions