Created
May 23, 2011 23:20
-
-
Save zerowidth/987844 to your computer and use it in GitHub Desktop.
test out truncating a file in place
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env ruby | |
log = "big.log" | |
words = %w(foo bar baz blech mumble what no ack aiee) | |
File.open(log, 'w') do |file| | |
1000.times do |n| | |
content = (0..(rand(100) + 10)).map { words[rand(words.size)] } | |
file.puts "#{n} #{content.join ' '}" | |
end | |
end | |
reader = File.open(log, 'r') | |
writer = File.open(log, 'r+') | |
writer.rewind | |
# assume no overlap between reading and writing! | |
reader.each_line.with_index do |line, n| | |
next if n < 10 | |
writer.puts line | |
end | |
writer.truncate(writer.pos) | |
reader.close | |
writer.close |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment