93

All I want to do is get all the content from a local file and store it in a variable. How?

File.read(@icon.full_filename).each {|l| r += l}

only gives me a part of it. In PHP, I just used file_get_contents.

1
  • 1
    I feel this is a uniquely Windows problem, because this solution, and the one proposed by zed_0xff work perfectly fine on Mac/Linux. I know that irb turns \r\n to \n when doing File.read... perhaps that's relevant here? Commented Jun 16, 2010 at 17:18

3 Answers 3

185
data = File.read("/path/to/file") 
Sign up to request clarification or add additional context in comments.

5 Comments

I thought that, but that gives me a string of length 52. The actual file size when I go File.size("/path/to/file") is 1676.
Doesn't that leave the file open?
I like this one! It would be nice to know how to keep the headers from file content type
This is useful to read without use of a block, allowing contents to be easily parsed and set to variables available to other blocks without the need for creating a class.
To address @TomRossi's question -- no, this does not leave the file open. Calling read on the File class opens, reads, and closes the file. However, calling read on an instance of file (which had to be opened first) does not close it. The method being called here is ruby-doc.org/core-2.5.0/IO.html#method-c-read as opposed to ruby-doc.org/core-2.5.0/IO.html#method-i-read
19

I think you should consider using IO.binread("/path/to/file") if you have a recent ruby interpreter (i.e. >= 1.9.2)

You could find IO class documentation here http://www.ruby-doc.org/core-2.1.2/IO.html

1 Comment

This is shorter and closes the file for you.
16

Answering my own question here... turns out it's a Windows only quirk that happens when reading binary files (in my case a JPEG) that requires an additional flag in the open or File.open function call. I revised it to open("/path/to/file", 'rb') {|io| a = a + io.read} and all was fine.

2 Comments

Unless you're actually concatenating a bunch of files together, I'd just write that as: data = File.open("file", "rb") {|io| io.read}
You sir, deserve a medal. I lost hours trying to figure out why my PDF attachments were unreadable when sent from a Windows server until I stumbled upon this answer.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.