Reputation: 2934
I am accessing a file, 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")
Upvotes: 7
Views: 7569
Reputation: 38576
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:
Upvotes: 6
Reputation: 23880
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
Upvotes: 4
Reputation: 5001
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
}
Upvotes: 1