Stream: helpdesk (published)

Topic: ✔ confused about IOBuffer


view this post on Zulip Leandro Martínez (Jul 03 2024 at 13:27):

Here I want to iterate over the lines of a generated buffer:

julia> io = IOBuffer(); write(io, "abc\n"); write(io, "def")
3

julia> for line in eachline(io)
           @show line
       end

julia>

Clearly, it does not work. I have to convert the io object to a string, then I try:

julia> io = IOBuffer(); write(io, "abc\n"); write(io, "def")
3

julia> for line in eachline(String(take!(io)))
           @show line
       end
ERROR: SystemError: opening file "abc\ndef": No such file or directory

which fails, because eachline expects a filename, or a IOBuffer. Thus,
I have to wrap the string again in a IOBuffer to make that work:

julia> io = IOBuffer(); write(io, "abc\n"); write(io, "def")
3

julia> str = String(take!(io))
"abc\ndef"

julia> for line in eachline(IOBuffer(str))
           @show line
       end
line = "abc"
line = "def"

That feels a little odd. Is there a more reasonable approach to iterate over the lines of the originally written io object without having to
first convert it to string and then wrap it again in a IOBuffer?

view this post on Zulip Gunnar Farnebäck (Jul 03 2024 at 13:33):

Try seekstart. It's the position in the buffer which trips you up.

view this post on Zulip Notification Bot (Jul 03 2024 at 14:03):

Leandro Martínez has marked this topic as resolved.

view this post on Zulip Leandro Martínez (Jul 03 2024 at 14:03):

Thanks!


Last updated: Dec 28 2024 at 04:38 UTC