Todd Benson
9/29/2008 3:55:00 AM
On Sun, Sep 28, 2008 at 7:59 PM, Procek <proc.procek@gmail.com> wrote:
> Hi!
>
> 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?
>
> ######## CUT HERE ########
> #Constans
> FS = 0x1c
> RS = 0x1e
>
> #Open file
> f = File.new("abcdef", "r")
>
> #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 ########
I'm not sure exactly what you are trying to do, but I have a guess. I
wouldn't really use readline or getc for this...
FS = 0x1c
RS = 0x1e
#your hex string
hex = "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"
#change it to your real data
s = hex.split.map {|i| i.to_i(16).chr}.join
#=> "171_512_12\036304_512_9\036\034abcdefghijkl012345678"
info, data = s.split(FS.chr)
lengths = info.split(RS.chr).map {|i| i.split(/_/).last}
data_array = []
lengths.each {|len| data_array << data.slice!(0, len.to_i)}
p data_array
...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
hth,
Todd