简体   繁体   中英

How to seek negative off the current position in file?

I'm trying to seek 2 bytes backwards from current position in ruby. The following code tries to find previous end of line.

    1.9.3-p448 :003 > while file.getc != '\n'
    1.9.3-p448 :004?>   file.seek(-2,IO::SEEK_CUR)
    1.9.3-p448 :005?>   end
    Errno::EINVAL: Invalid argument - test
    from (irb):4:in `seek'
    from (irb):4
    from /usr/local/rvm/rubies/ruby-1.9.3-p448/bin/irb:16:in `<main>'

I'm unable to understand why I'm getting this error. It seeks perfectly outside loop (the same statement). test is the filename.

I'd guess that your problem is that you're not two bytes into the file yet. I just did this with a simple text file:

>> fp = File.new('pancakes.txt', 'r')
>> fp.readline
>> fp.seek(-2, IO::SEEK_CUR)
=> 0
>> fp.seek(-20, IO::SEEK_CUR)
Errno::EINVAL: Invalid argument - x.txt

The first line of the file was only a couple characters long so -20 would try to put me before the beginning of the file.

I think you just need to throw a pos check into the mix: if file.pos == 0 then you're at the beginning and a negative seek will raise an exception.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM