What does iswritable(io)
actually mean? I thought it would mean it would accept write(io, stuf...)
but apparently not?
julia> f = open("tmp", "w");
julia> iswritable(f)
true
julia> write(f, "hi")
2
julia> close(f)
julia> iswritable(f)
true
julia> write(f, "hi")
0
Should I check isopen
and iswritable
maybe?
yes, I think so
iswritable
checks whether your io
is readonly or not:
julia> io = IOBuffer("asd")
IOBuffer(data=UInt8[...], readable=true, writable=false, seekable=true, append=false, size=3, maxsize=Inf, ptr=1, mark=-1)
julia> iswritable(io)
false
julia> write(io, "asd")
ERROR: ArgumentError: ensureroom failed, IOBuffer is not writeable
Right. I thought that iswritable
would imply isopen
.
It seems that many streams don't define iswritable
so it looks like the most fail-safe way is to just try. And since e.g. IOStream
does not even throw
julia> io = open("test.txt", "w")
close(io)
write(io, "hello")
0
it looks like you have to verify that the number of written bytes is what you expect? Something like
julia> io = open("test.txt", "w")
close(io)
txt = "hello"
nb = sizeof(txt)
n = write(io, txt)
if n != nb
error("could not write")
end
ERROR: could not write
Stacktrace:
[1] error(s::String)
@ Base ./error.jl:33
[2] top-level scope
@ REPL[3]:7
What is the benefit of write
not throwing and instead returning 0
here?
It seems inconsistent that if the stream is not writable it throws but if it is closed it returns 0. Why not either return 0 in both cases or throw in both cases?
Python throws:
>>> with open("file.txt", "w") as io:
... io.write("hello")
... io.close()
... io.write("world")
...
5
Traceback (most recent call last):
File "<stdin>", line 4, in <module>
ValueError: I/O operation on closed file.
Well spotted:point_up: maybe there's a conclusive reason for that, but I'd definitely expect it to throw, too
https://github.com/JuliaLang/julia/issues/1701 seems to suggest it is intentional and https://linux.die.net/man/2/write says up to n bytes.
Last updated: Nov 06 2024 at 04:40 UTC