From 6affbd66d446723acd3e78683dec3d0d1c048eee Mon Sep 17 00:00:00 2001 From: Julien Portalier Date: Tue, 13 Jun 2017 11:13:00 +0200 Subject: [PATCH] Fix: IO::FileDescriptor#seek from current position Trying to seek from the current position failed because the system position of a buffered IO is different from the actual position in the stream. --- spec/std/file_spec.cr | 7 +++++++ src/io/file_descriptor.cr | 8 +++++++- 2 files changed, 14 insertions(+), 1 deletion(-) diff --git a/spec/std/file_spec.cr b/spec/std/file_spec.cr index e039e332e7f5..4a08b7d10110 100644 --- a/spec/std/file_spec.cr +++ b/spec/std/file_spec.cr @@ -621,6 +621,13 @@ describe "File" do file.gets(4).should eq("ello") end + it "seeks from the current position" do + file = File.new("#{__DIR__}/data/test_file.txt") + file.gets(5) + file.seek(-4, IO::Seek::Current) + file.tell.should eq(1) + end + it "raises if invoking seek with a closed file" do file = File.new("#{__DIR__}/data/test_file.txt") file.close diff --git a/src/io/file_descriptor.cr b/src/io/file_descriptor.cr index 7122f216a936..24406aa48b19 100644 --- a/src/io/file_descriptor.cr +++ b/src/io/file_descriptor.cr @@ -131,7 +131,13 @@ class IO::FileDescriptor check_open flush - seek_value = LibC.lseek(@fd, offset, whence) + + if whence.current? + seek_value = LibC.lseek(@fd, tell + offset, Seek::Set) + else + seek_value = LibC.lseek(@fd, offset, whence) + end + if seek_value == -1 raise Errno.new "Unable to seek" end