I’m trying to read a file using ruby. Firsty I use readline twice,
then I wan’t to read some part of data, but I don’t get where I have a
mistake. Could you help me find it?
#Read a line, split it, and delete bad fields (last one)
tbl = f.readline(FS.chr).split(RS.chr) - [FS.chr] #For each from tbl
tbl.each { |x| #Split field
splitted = x.split("_") #The read loop
tmp = String.new
i=0
while (i < splitted[2].to_i)
tmp += f.getc.chr #Here I have an error…
end #Save readed data
f2 = File.new(s[0]+"-"+s[1]+".txt", “w”)
f2.write(tmp)
f2.close
}
#Close file
f.close
######## CUT HERE ########
The test file in HEX (beacouse it have non-printable chars)
######## CUT HERE ########
31 37 31 5f 35 31 32 5f 31 32 1e 33 30 34 5f 35 31 32 5f 39 1e 1c 61
62 63 64 65 66 67 68 69 6a 6b 6c 30 31 32 33 34 35 36 37 38
######## CUT HERE ########
…Your test file isn’t long enough for me to establish the actual
layout, so I had to make educated guesses. When reading a file you
can wrap your code up like…
File.open( ‘my_file’, ‘r’) do |f| #parsing code in here
end
At Mon, 29 Sep 2008 09:59:18 +0900,
Procek wrote in [ruby-talk:316286]:
i=0
while (i < splitted[2].to_i)
tmp += f.getc.chr #Here I have an error…
end
This is an inifinite loop.
splitted[2].to_i.times do
end
or
tmp = f.read(splitted[2].to_i)
work.
FS = “\x1c”
RS = “\x1e”
File.open(“abcdef”, “rb”) do |f|
f.gets(FS).chomp(FS).split(RS).each do |x|
s = x.split("_")
tmp = f.read(s[2].to_i)
File.open(s[0]+"-"+s[1]+".txt", “w”) {|f2| f2.write(tmp)}
end
end
This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.