Step down at my blog with your ideas,comments,suggestions on Ruby on Rails, PHP or Web2.0 Technology.

Thursday, June 29, 2006

SWAP FILES

Ruby n RAJ
# swapping the contents of TWO files

# display before swapping
puts'========== BEFORE SWAPPING ============'
f1=File.open('file1.txt','r') do |f1|
puts'FILE1 contents : '
while(line=f1.gets)
puts line
end
end
f2=File.open('file2.txt','r') do |f2|
puts'FILE2 contents : '
while(line=f2.gets)
puts line
end
end

# copy the contents of FILE1 to TEMP_FILE
ftemp=File.open('temp.txt','w') do |ftemp|
f1=File.open('file1.txt','r') do |f1|
while(line=f1.gets)
ftemp.puts line
end
end
end

# copy the contents of FILE2 to FILE1
f1=File.open('file1.txt','w') do |f1|
f2=File.open('file2.txt','r') do |f2|
while(line=f2.gets)
f1.puts line
end
end
end


# copy the contents of TEMP_FILE to FILE2
f2=File.open('file2.txt','w') do |f2|
ftemp=File.open('temp.txt','r') do |ftemp|
while(line=ftemp.gets)
f2.puts line
end
end
end


# display AFTER swapping
puts'========== AFTER SWAPPING ============'
f1=File.open('file1.txt','r') do |f1|
puts'FILE1 contents : '
while(line=f1.gets)
puts line
end
end
f2=File.open('file2.txt','r') do |f2|
puts'FILE2 contents : '
while(line=f2.gets)
puts line
end
end
OUTPUT
C:\ruby\bp>ruby swapcontents.rb
========== BEFORE SWAPPING ============
FILE1 contents :
I want to be a good programmer in RoR
Please help me.
FILE2 contents :
Shall I proceed with Ruby or Not?
========== AFTER SWAPPING ============
FILE1 contents :
Shall I proceed with Ruby or Not?
FILE2 contents :
I want to be a good programmer in RoR
Please help me.

0 Comments:

Post a Comment

<< Home