Ruby – An issue with Ruby script output stored in a file

An issue with Ruby script output stored in a file… here is a solution to the problem.

An issue with Ruby script output stored in a file

I have a Ruby script that outputs a bunch of text. For example:

puts "line 1"
puts "line 2"
puts "line 3"
# etc... (obviously, this isn't how my script works..)

Not a lot of data – there may be about 8kb of character data in total.

When I run the script on the command line, it works as expected :

$ ./my-script.rb

line 1
line 2
line 3

However, when I insert it into the file, the output is truncated to exactly 4096 bytes:

$ ./my-script.rb > output.txt

What causes it to stop at 4kb?

Update: I just rewrote the script to output directly to a file instead of printing to screen and capturing output, the problem is still there!

$output = File.new("file.txt")
$output << "line 1"  #etc..

Solution

Did your program terminate correctly? 4kB can be the size of the operating system’s internal buffer for I/O, and when your program terminates abruptly or not at all, the following data present in the next buffer (up to 8kB, which is the total size of your data) will be lost.

Related Problems and Solutions