Forum: Ruby size change after file writing

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
Li C. (Guest)
on 2007-07-30 22:50
Hi all,

I write a small script to read old files and write to new files. Either
reading line by line or whole file at once then I ask Ruby to write to
new files. The new file is much smaller than the old one. I also find
that the new file losses many information. How to explain this?

Thanks,

Li

#################script-1 read file line by line and write to a new file
path='C:\\Allo12-Y2'
file_names=[]

Dir.open(path).each do|f|
              file_names<<path+"\\#{f}" unless f=~/^\.\.*$/
end

file_names.each do|f|
       new_file=File.open("#{f}b",'w')
       File.open(f,'r') do|file|
       file.each_line{|line|new_file.print line }
       end
end


###################sctript-2 read whole file and write to a new file


path='C:\\Allo12-Y2'
file_names=[]

Dir.open(path).each do|f|
              file_names<<path+"\\#{f}" unless f=~/^\.\.*$/
end


file_names.each do|f|
      file=File.open(f,'r')                  #open file for read
      new_file=File.open("#{f}b",'w')#open file for write
      new_file.print file.read               #write old file to new file
end

### size in old file: AlloY2.001  is 609kb
    size in new file: AlloY2.001b  is 47bk
Nobuyoshi N. (Guest)
on 2007-07-30 23:44
(Received via mailing list)
Hi,

At Tue, 31 Jul 2007 03:50:24 +0900,
Li Chen wrote in [ruby-talk:262503]:
> I write a small script to read old files and write to new files. Either
> reading line by line or whole file at once then I ask Ruby to write to
> new files. The new file is much smaller than the old one. I also find
> that the new file losses many information. How to explain this?

Use "rb" and "wb" mode for binary files, or better, use FileUtils.cp.
Li C. (Guest)
on 2007-07-30 23:59
Nobuyoshi N. wrote:

> Use "rb" and "wb" mode for binary files, or better, use FileUtils.cp.

Thank you very much and they work well.

Li
This topic is locked and can not be replied to.