End of file error when trying to Marshal.load

Hi,-

I am trying out the marshaling functionality of Ruby with this
documentation as a guide:

http://www.ruby-doc.org/core/classes/Marshal.html

Code goes like this:


class Klass
def initialize(str)
@str = str
end
def sayHello
@str
end
end

def marshalKlass
o = Klass.new(“hello\n”)
print o.sayHello
Marshal.dump(o, File.open(“output.txt”, “w”))
data = File.open(“output.txt”) # all fine up until here
obj = Marshal.load(data) # EOFError
print obj.sayHello
end

if FILE == $PROGRAM_NAME
marshalKlass
end


The line:
obj = Marshal.load(data)
gives the following error:

Klass.rb:19:in load': end of file reached (EOFError) from Klass.rb:19:in marshalKlass’
from Klass.rb:32

The line:
data = File.open(“output.txt”) places the cursor at the start of the
file. What’s wrong?

Thanks!

/ Vahagn

Vahagn H. wrote:

file. What’s wrong?
I’m guessing you’re on Windows. You need to open the file in binary
mode. That is, with “wb” and “rb”.

Tim, I’m on Mac OS X (Leopard). Now I have:

Marshal.dump(o, File.open(“output.txt”, “wb”))
data = File.open(“output.txt”, “rb”)
obj = Marshal.load(data)

But I get the exact same error.

/ Vahagn

Tim H. wrote:

Vahagn H. wrote:

file. What’s wrong?
I’m guessing you’re on Windows. You need to open the file in binary
mode. That is, with “wb” and “rb”.

Please do not top post.

On 05.09.2009 13:45, Vahagn H. wrote:

Tim H. wrote:

Vahagn H. wrote:

file. What’s wrong?
I’m guessing you’re on Windows. You need to open the file in binary
mode. That is, with “wb” and “rb”.

You also need to make sure you write the complete file which you don’t
because you’re not closing the File properly.

http://blog.rubybestpractices.com/posts/rklemme/001-Using_blocks_for_Robustness.html

Cheers

robert

On 05.09.2009 14:35, Vahagn H. wrote:

print o.sayHello
dumped = File.open(“output.txt”, “w”)
Marshal.dump(o, dumped)
dumped.close
data = File.open(“output.txt”, “r”)
obj = Marshal.load(data)
data.close
print obj.sayHello
end

This is better but my point in the blog article was a different one:
use the block form of File.open because it is more robust.

Cheers

robert

@Robert: Sure!

def marshal_class
o = Klass.new(“hello”)
print o.sayHello, " from original object\n"
File.open(“data.txt”, “w”) do |file|
Marshal.dump(o, file)
end
File.open(“data.txt”, “r”) do |file|
@obj = Marshal.load(file)
end
print @obj.sayHello + " from restored object\n"
end

That’s a good article, btw.
Cheers,
Vahagn

@Robert:

Ah! “While not closing a read only file usually does not have dramatic
consequences, not closing a file opened for writing likely has dramatic
consequences.”

The working method:

def marshalKlass
o = Klass.new(“hello\n”)
print o.sayHello
dumped = File.open(“output.txt”, “w”)
Marshal.dump(o, dumped)
dumped.close
data = File.open(“output.txt”, “r”)
obj = Marshal.load(data)
data.close
print obj.sayHello
end

Thanks,
/ Vahagn