If you write line breaks to a file under windows, the write and syswrite
methods count a line break as one character, not two, meaning that the
value returned is incorrect.
e.g…
File.open(‘arr.txt’, ‘w’) do |file|
arr = [ “123\n”, “456” ]
puts file.write(arr)
end
This bit of code displays the number 7 on the screen. The actual size
of the file is 8. This is causing me problems with File#truncate,
becuase I’m truncating too much of the file!
If you write line breaks to a file under windows, the write and syswrite
methods count a line break as one character, not two, meaning that the
value returned is incorrect.
e.g…
File.open(‘arr.txt’, ‘w’) do |file|
arr = [ “123\n”, “456” ]
puts file.write(arr)
end
This bit of code displays the number 7 on the screen. The actual size
of the file is 8. This is causing me problems with File#truncate,
becuase I’m truncating too much of the file!
By all means, but it’s a bug in Windows, not Ruby.
Printers require both \r and \n to go to a new line. DOS decided that
instead of converting output to the printer, text files should be stored
with \r\n, but when read or written to, these should be converted to
\n. Naturally, this braindead design screws up the file position.
Linux doesn’t do this at all, and Macs only use \r, IIRC.
To get around this, open the file in binary mode (by including b in the
mode string). Note that you will then need to give text files a \r\n
separator, or Notepad will barf. (Wordpad can handle normal files,
though.)
···
On Tue, 2003-05-20 at 11:33, Alan Davies wrote:
I’ve fixed my truncate problems by using IO#pos instead, but this is a
bug that needs to be adresssed surely?
By all means, but it’s a bug in Windows, not Ruby.
I was about to disagree with you because I thought that the C runtime
did not have this problem but is seems that it does indeed do the same
thing…
“The fwrite function writes up to count items, of size length each, from
buffer to the output stream. The file pointer associated with stream (if
there is one) is incremented by the number of bytes actually written. If
stream is opened in text mode, each carriage return is replaced with a
carriage-return linefeed pair. The replacement has no effect on the
return value.”
I have to agree that this is one of the more ridiculous “features” of
DOS/Windows. Its very legacy and there is no need for it any more, but
I suppose that if they got rid of it, lots of stuff would break.