Dude, where's my carriage returns?

  • Thread starter Karl von Laudermann
  • Start date
K

Karl von Laudermann

I'm trying to write a tiny Ruby program that will print the ascii
values of all characters in a text file. I'm doing this to help debug a
bash script, which runs under Cygwin on Windows, that makes changes to
a text file, but I suspect isn't adding carriage returns before each
line feed. My Ruby program looks like this:

--------------
fn = ARGV[0]
count = 0

File.open(fn, "r") do |f|
f.each_byte do |ch|
print "#{ch} "
count += 1
end
end

puts
puts "Count = #{count}"
-------------

When I run it on a small text file that looks like this...

-------------
hello
world
-------------

....I get the following output:

-------------
104 101 108 108 111 10 119 111 114 108 100
Count = 11
-------------

However, since I'm creating this text file in Windows Notepad, I know
that there should be a carriage return before the line feed, and the
output *should* actually be:

-------------
104 101 108 108 111 13 10 119 111 114 108 100
Count = 12
-------------

Note the 13 (CR) before the 10 (LF).

If I use Windows to look at the file properties, it confirms that the
file is actually 12 bytes in size. If I add more line breaks, the file
size increases by two for each one, while the "Count" value in the Ruby
script's output increases by only one byte for each, and no byte of
value 13 is ever displayed.

How can I get Ruby to actually read carriage return characters from a
file?
 
J

James Edward Gray II

fn = ARGV[0]
count = 0

File.open(fn, "r") do |f|

File.open(fn, "rb") do |f|
f.each_byte do |ch|
print "#{ch} "
count += 1
end
end

puts
puts "Count = #{count}"

Try the above fix to open the file in "binary" mode, shutting off
line-ending translation.

James Edward Gray II
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,982
Messages
2,570,186
Members
46,740
Latest member
JudsonFrie

Latest Threads

Top