tags:

views:

788

answers:

3

Hey guys, probably a simple question but my google-fu is failing me and does not seem to be posted on SO yet...

I basically have a file I am accessing and before I append to it I want to delete the last line from the file. Is there any efficient way of doing this in Ruby?

This is what I am using to access the file:

file = File.new("imcs2.xml", "a")
A: 

The easiest way is just to read the whole file, remove the '\n' at the end, and rewrite it all with your own content:

filename = "imcs2.xml"
content = File.open(filename, "rb") { |io| io.read }
File.open(filename, "wb") { |io|
    io.print content.chomp
    io.print "yourstuff"    # Your Stuff Goes Here
}

Alternatively, just io.seek() backwards over the last newline if any:

filename = "imcs2.xml"
File.open(filename, "a") { |io|
    io.seek(-1, IO::SEEK_CUR)  # -1 for Linux, -2 for Windows: \n or \r\n
    io.print "yourstuff"    # Your Stuff Goes Here
}
Rutger Nijlunsing
+1  A: 

Assuming you want to remove the entire last line of the file, you can use this method which locates the start of the last line and begins writing from there:

last_line = 0
file = File.open(filename, 'r+')
file.each {  last_line = file.pos unless file.eof? }

file.seek(last_line, IO::SEEK_SET)
#Write your own stuff here
file.close
Pesto
+4  A: 

I'm not gonna try to guess what you're trying to do, but if you're trying to get rid of the closing tag of the root element in an XML file so that you can add more child tags, then re-add the closing root tag, I would imagine that there are ruby modules out there that facilitate this task of writing/editing XML. Just sayin.

Perhaps Builder:

hpricot also seems to work:

Jorge Israel Peña
You should get a job as a psychic :). That is exactly what I was trying to do, it is a small hack job which is why I didn't do too much research into it, but thanks for going the extra mile!
Javed Ahamed
No problem! Sorry I didn't post a definitive answer, but I'm almost positive there are tools out there that will do this for you. I searched around for about 15 minutes and I found these. Of course, you with the motivation of finishing your project are bound to find more, probably better solutions, in case the ones I provided don't suffice.
Jorge Israel Peña