Appending to file in arbitrary position

T

Tulsi Das

Hi, I'm implementing the server side of a file upload with resume option
part of a web app.

The client sends the last position so I have to append to the existing
file from that position.

Current code is:

@uploadfile = @params["uploadfile"]
content_range = @request.env['HTTP_CONTENT_RANGE']
filename = @uploadfile.original_filename
data = @uploadfile.read

# position to append from
pos = content_range[/\d+/].to_i

f = File.open("#{filename}", "a")
#f.pos = pos
f.seek(pos)
f.write(data)
f.close

I've tried opening the file with a and a+ modes. I've tried doing
rewing, setting pos (like the commented line) and seek, and none of them
works, the new data is always appended at the end of the file.

Any clues?

Thanks
 
J

Jamey Cribbs

Tulsi said:
Hi, I'm implementing the server side of a file upload with resume option
part of a web app.

The client sends the last position so I have to append to the existing
file from that position.

Current code is:

@uploadfile = @params["uploadfile"]
content_range = @request.env['HTTP_CONTENT_RANGE']
filename = @uploadfile.original_filename
data = @uploadfile.read

# position to append from
pos = content_range[/\d+/].to_i

f = File.open("#{filename}", "a")
#f.pos = pos
f.seek(pos)
f.write(data)
f.close

I've tried opening the file with a and a+ modes. I've tried doing
rewing, setting pos (like the commented line) and seek, and none of them
works, the new data is always appended at the end of the file.

Open the file in r+ mode. This is read-write mode that starts at the
beginning of the file and allows you to seek to a specific position.

Jamey
 
T

Tulsi Das

Jamey said:
Open the file in r+ mode. This is read-write mode that starts at the
beginning of the file and allows you to seek to a specific position.

I can't believe it was so easy, I've never even read the "r" section,
assuming it was read only... thanks a lot, it works great!
 
A

Austin Ziegler

I can't believe it was so easy, I've never even read the "r" section,
assuming it was read only... thanks a lot, it works great!

If you want this to be cross-platform, make sure you actually open it
"rb+" or your code will mysteriously fail on Windows.

-austin
 

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

No members online now.

Forum statistics

Threads
473,969
Messages
2,570,161
Members
46,710
Latest member
bernietqt

Latest Threads

Top