Assume you have the habit to use the variable fid
as an IOStream
-variable and you are not sure, if the related file is still open (it might be that a process has crashed or you have forgotten to close the old not longer used IOStream
properly), how could you reuse this file name without a restart of Julia?
Here my proposal:
function MyLibOpenTxtIOStream(_fn::AbstractString, _fid::String, _openTxtIOStream::Bool=true)
getvars() = [string(v) for v in sort!(names(Main)) if isdefined(Main, v) && !(v in (:Base, :Main, :Core, :InteractiveUtils, :ans))]
if ispath(_fn)
if any(occursin.(_fid, getvars()))
_s = Symbol(_fid)
if @eval(Base.@isdefined($_s))
if @eval(isa($_s, IOStream))
@eval(close($_s))
GC.gc() # garbage collection
end
end
end
rm(_fn, force = true)
end
_dir, _ = splitdir(_fn)
if ispath(_dir)
if _openTxtIOStream
return open(_fn, "w")
else
return missing
end
else
error("Path does not exist!")
end
end
fid = open_new_IOStream("/tmp/file.txt", "fid")
Now my question: Is this code somehow fishy?
Remark:
The getvars()
is taken from: Recommended way to delete user-defined variables