Hi,
does somebody know, how to disable the auto-conversion of a 2-byte
sequence of 0x0D 0x0A into a single byte '\n'?
I want to process binary data, which can contain such byte sequences but
not idicating end-of-line as the file has a fix record length.
Please take the example below:
# input file "test.dat" contains 2 bytes: 0x0D and 0x0A
# the result file should contain 0x0A 0x0D in this example
dest = File.new("test.dat", "r")
a = dest.sysread(1) # should read 1 byte (0x0D), but does read both in
reality as '\n'
b = dest.sysread(1) # should read 1 byte (0x0A), but gets EOF/nil in
consequence of above
dest.close
dest = File.new("result.dat", "w")
dest.syswrite(b)
dest.syswrite(a)
dest.close
input file “test.dat” contains 2 bytes: 0x0D and 0x0A
the result file should contain 0x0A 0x0D in this example
dest = File.new(“test.dat”, “r”)
–
Pierre Baillet
Avec un escalier prévu pour la montée, on reussi souvent à monter
plus bas qu’on ne serait descendu avec un escalier prévu pour la descente.
Devise Shadok
I want to process binary data, which can contain such byte sequences
but not indicating end-of-line as the file has a fix record length.
Best regards,
Frank
And here’s an example.
#---------
FIXREC_LEN = 10
FIXPAD_CHR = ‘!’
File.open(‘result.dat’, ‘wb’) do |fo|
File.open(‘test.dat’, ‘rb’) do |fi|
until fi.eof
dat = fi.read(FIXREC_LEN)
p [dat, dat[4], dat[5]]
dat_new = dat.gsub(/\r\n/, “\n\r”)
fo.write(dat_new << FIXPAD_CHR * (FIXREC_LEN-dat.size))
end
end
end # files close automatically for File.open {block}
puts ‘-’ * 30
File.open(‘result.dat’, ‘rb’) do |fi|
until fi.eof
dat = fi.read(FIXREC_LEN)
p [dat, dat[4], dat[5]]
end
end #---------
For all, interesting in this question: alternativ to the method
“binmode”,
it works with File.new(“test.dat”, “rb”) as well, opening the binary-IO.
Cheers, Frank
···
-----Ursprüngliche Nachricht-----
Von: Pierre Baillet [mailto:oct@zoy.org]
Gesendet: Dienstag, 3. Juni 2003 13:38
An: ruby-talk@ruby-lang.org
Cc: rheinmainruby@eylerfamily.org
Betreff: Re: file I/O: how can I disable auto-convert of the 2-byte
sequence 0x0D, 0x0A into a single byte ‘\n’?
On Tue, Jun 03, 2003, Polscheit, Frank wrote:
input file “test.dat” contains 2 bytes: 0x0D and 0x0A
the result file should contain 0x0A 0x0D in this example
dest = File.new(“test.dat”, “r”)
Have you tried switching to binary mode ?
dest.binmode
Cheers !
Pierre Baillet
Avec un escalier prévu pour la montée, on reussi souvent à monter
plus bas qu’on ne serait descendu avec un escalier prévu pour la
descente.
Devise Shadok