tempfile iterator?

T

tony summerfelt

what's the easiest way to iterate through a Tempfile?

basically i want to append the contents of a tempfile (created by
Tempfile.new) to the end of a regular file (created by File.open)
 
A

Ara.T.Howard

what's the easiest way to iterate through a Tempfile?

basically i want to append the contents of a tempfile (created by
Tempfile.new) to the end of a regular file (created by File.open)

t = Tempfile.new $$
t.puts 42
t.close
t.open

# or t.flush

open('file','a+'){|f| f.write t.read}

-a
--
===============================================================================
| EMAIL :: Ara [dot] T [dot] Howard [at] noaa [dot] gov
| PHONE :: 303.497.6469
| A flower falls, even though we love it;
| and a weed grows, even though we do not love it.
| --Dogen
===============================================================================
 
M

Mark Sparshatt

tony said:
i have a file '@lg' the file already exists, so i used:

tlf.open

open('@lg','a') {|f| f.write tlf.read}

but the contents of the temprorary file created as tlf were not
appended to the filename in '@lg'
if @lg is a variable holding the filename then that should be

open(@lg, 'a') {|f| f.write tlf.read}

The code you wrote would be trying to append to a file called '@lg'
 
R

Robert Klemme

tony summerfelt said:
yup. i figured that out when i applied some common sense...

for some reason, with that line it the thread is hanging...i might
have to rethink the way i've done things :)

Maybe you forgot to seek?

Note also, taht "f.write tlf.read" will slurp the whole file into mem
before writing it out again. This may or may not be a problem, depending
on the size of your file.

Taking this together you might want to do this:

# reset file position of the open Tempfile
tlf.seek 0

# copy in chunks
open(@lg,'a') do |f|
while ( data = tlf.read 1024 )
f.write data
end
end

Regards

robert
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
474,149
Messages
2,570,842
Members
47,388
Latest member
EarthaGilm

Latest Threads

Top