Crazy Dan 11
Crazy Dan 11

Reputation: 237

Ruby Premature EOF?

I'm trying to write one file into another one in Ruby, but the output seems to stop prematurely.

Input file - large CSS file with base64 embedded fonts

Output file - basic html file.

#write some HTML before the CSS (works)
...
#write the external CSS (doesn't work, output finished prematurely)
while !ext_css_file.eof()        
    out_file.puts(ext_css_file.read())
end
...
#write some HTML after the CSS (works)

The resulting file is basically a valid HTML file, with a truncated CSS (in the middle of an embedded font)

When doing a puts on the result of read(), I get the same result: The CSS file is read only up to this last string: "RMSHhoPCAGt/mELDBESFBQSggGfAgESKCUAAAAAAAwAlgABAAAAAAABAAUADAABAAAAAAAC"

Upvotes: 1

Views: 390

Answers (1)

Midwire
Midwire

Reputation: 1100

It is difficult to provide a detailed solution without more insight into what the CSS file actually contains. Based on your code above, I would try something like this instead:

#write some HTML before the CSS (works)
...
#write the external CSS (doesn't work, output finished prematurely)
out_file.puts(ext_css_file.read())
...
#write some HTML after the CSS (works)

I don't think you need the .eof check because the read method reads and returns the entire file contents, or an empty string or nil if at the end of file. See here: http://apidock.com/ruby/IO/read

I would tend to read and write the same type of data. For instance if I were writing data into the new file using puts, I would read data using readlines. If I were writing binary data using write, I would read the data using read. I would be consistent with either strings or bytes and not mix the two.

Try something like this...

File.open('writable_file_path', 'w') do |f|
  # f.puts "some html"
  f.puts IO.readlines('css_file_path')
  # f.puts "some more html"
end

Upvotes: 1

Related Questions