Stream: helpdesk (published)

Topic: Seek relative to the end of a file or stream?


view this post on Zulip Mark Kittisopikul (Oct 27 2023 at 01:44):

Is there any direct way to seek relative to the end of a file or stream with a single call? For example, C and Python allow you set a positive negative offset relative to SEEK_END via fseek or lseek. Cross posted from Slack.

view this post on Zulip Sebastian Pfitzner (Oct 27 2023 at 08:35):

I think the best you can do is seek(io, length(io)-x). Adding a two-arg seekend seems reasonable to me though

view this post on Zulip Nathan Zimmerberg (Oct 27 2023 at 14:14):

What is the advantage of a two-arg seekend instead of a read or write directly to an offset? For example libUV doesn't support seeking files https://github.com/libuv/libuv/issues/2378 but does allow an additional argument offset to read and write.

view this post on Zulip Nathan Zimmerberg (Oct 27 2023 at 14:36):

Also from what I can tell, length is not documented to work on files or streams. You could do:

function fsize(x)
    seekend(x)
    position(x)
end

To get the file size before doing the seek.

view this post on Zulip Brenhin Keller (Oct 27 2023 at 15:22):

StaticTools.jl fseek has SEEK_END :julia-troll:

view this post on Zulip Brenhin Keller (Oct 27 2023 at 15:23):

but yeah, not the most kosher package

view this post on Zulip Mark Kittisopikul (Oct 27 2023 at 17:25):

Currently we have the following

function seekend(f::File)
    ret = ccall(:jl_lseek, Int64, (OS_HANDLE, Int64, Int32), f.handle, 0, SEEK_END)
    ret == -1 && (@static Sys.iswindows() ? windowserror : systemerror)("seekend")
    return f
end

Could we do this instead?

function seekend(f::File, n::Integer=0)
    ret = ccall(:jl_lseek, Int64, (OS_HANDLE, Int64, Int32), f.handle, n, SEEK_END)
    ret == -1 && (@static Sys.iswindows() ? windowserror : systemerror)("seekend")
    return f
end

view this post on Zulip Brenhin Keller (Oct 27 2023 at 17:45):

looks like that ought to work AFAICT, except maybe should explicitly convert n to Int32 first if I'm looking at that right?

view this post on Zulip Mark Kittisopikul (Oct 27 2023 at 20:05):

n should be converted to Int64, but I think ccall will do that for us.

view this post on Zulip Mark Kittisopikul (Oct 28 2023 at 04:03):

https://github.com/JuliaLang/julia/pull/51908


Last updated: Nov 22 2024 at 04:41 UTC