Line ending problem.

S

sea__chan

Hi

I am writing a ruby script to insert some content into the beginning of
some files.

The files would be used in Windows or Mac, when I use File.puts method
to write the file, it changes the line ending of the file.

Any way to let ruby keep the previous line-ending of the file?

Thanks
 
J

jeremywoertink

Cong said:
Hi

I am writing a ruby script to insert some content into the beginning of
some files.

So you want to add stuff to the beginning of a file? Well, as far as I
know, you can't just add stuff to the beginning, you have to create a
new file, add your stuff, then append the old stuff at the end of the
new file.

new_file = File.new("your_new_file.txt", "w+")

new_file.write("I'm at the beginning\n")

IO.readlines("your_old_file.txt").each do |line|
new_file.write(line)
end

new_file.close


~Jeremy
 
X

Xavier Noria

I am writing a ruby script to insert some content into the beginning
of
some files.

The files would be used in Windows or Mac, when I use File.puts method
to write the file, it changes the line ending of the file.

Any way to let ruby keep the previous line-ending of the file?

Not automatically.

If you know before hand that the line-ending convention is uniform you
can open the file in binary mode, pick a few bytes, and look for the
first line separator (=~ /\015?\012/).

Then write in binary mode and set $\ to that capture, aka the ouput
record separator. Use print instead of puts, since puts does not check
$\ but prints "\n" unconditionally.

-- fxn
 
R

Rick DeNatale

Then write in binary mode and set $\ to that capture, aka the ouput
record separator. Use print instead of puts, since puts does not check
$\ but prints "\n" unconditionally.

I'd suggest that rather than this you use write instead of print or
puts and put the line breaks in explicitly.

My concern over using $\ is that it's global so it affects any other
Io objects, and I'm not sure it's a thread-safe global.
 

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,772
Messages
2,569,591
Members
45,100
Latest member
MelodeeFaj
Top