Forum: Ruby File.open not reading full file when repeatedly called.

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
Todd S. (Guest)
on 2006-04-26 01:31
I have a trange situation...

I have a read method which uses the syntax:
  data = File.open(myFile)
  data.each_line { |line|
    # read in the file
  }
  data.close


The file is 6311 lines long.

If I read in file_A and write it out to file_B I get a duplicate as
expected.
BUT if I, WITHOUT exiting the program read in file_B it will only read
in 6250 lines.

If I exit the program and restart with reading in file_B the entire file
is read.

Is this a memory problem with ruby?  Or should I be doing something
different when I read a file?
Logan C. (Guest)
on 2006-04-26 01:46
(Received via mailing list)
On Apr 25, 2006, at 5:31 PM, Todd S. wrote:

> The file is 6311 lines long.
> Is this a memory problem with ruby?  Or should I be doing something
> different when I read a file?
>
> --
> Posted via http://www.ruby-forum.com/.
>

Could you give more of your code please? (Also if you just want to
read the whole file into one string you can do File.read("filename") )
Ray B. (Guest)
on 2006-04-26 01:49
(Received via mailing list)
Todd S. wrote:
> The file is 6311 lines long.
> different when I read a file?
You need to flush the file buffer before you start reading.

You can do this either by closing the file_B after you have completed
writing it and then opening for reading, or by explicitly calling flush
on file_B.

--

Ray
Todd S. (Guest)
on 2006-04-26 02:48
I completely forgot to put the myFile.close call into the write routine.
Because the read was not getting all the data, that's where I was
looking for the problem.

Thanks both for your help.  Following up on your answers lead me to the
solution.
Robert K. (Guest)
on 2006-04-26 13:47
(Received via mailing list)
2006/4/26, Todd S. <removed_email_address@domain.invalid>:
> I completely forgot to put the myFile.close call into the write routine.

That's the reason why it's recommended to use the block form of
File.open().

Cheers

robert
This topic is locked and can not be replied to.