简体   繁体   English

如何从文件中的当前位置查找负数?

[英]How to seek negative off the current position in file?

I'm trying to seek 2 bytes backwards from current position in ruby. 我试图从红宝石的当前位置向后寻找2个字节。 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. 文件的第一行只有几个字符,因此-20会尝试将我放在文件开头之前。

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. 我认为您只需要对pos检查:如果file.pos == 0那么您就处于起步阶段,否定搜索将引发异常。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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