當前位置: 首頁>>編程示例 >>用法及示例精選 >>正文


Julia write用法及代碼示例

用法:

write(io::IO, x)
write(filename::AbstractString, x)

將值的規範二進製表示寫入給定的 I/O 流或文件。返回寫入流的字節數。另請參見 print 以編寫文本表示(使用可能取決於 io 的編碼)。

寫入值的字節順序取決於主機係統的字節順序。在寫入/讀取時(例如使用 htol ltoh )轉換為/從固定字節序轉換以獲得跨平台一致的結果。

您可以使用相同的write 調用寫入多個值。即以下是等效的:

write(io, x, y...)
write(io, x) + write(io, y...)

例子

一致的序列化:

julia> fname = tempname(); # random temporary filename

julia> open(fname,"w") do f
           # Make sure we write 64bit integer in little-endian byte order
           write(f,htol(Int64(42)))
       end
8

julia> open(fname,"r") do f
           # Convert back to host byte order and host integer type
           Int(ltoh(read(f,Int64)))
       end
42

合並寫調用:

julia> io = IOBuffer();

julia> write(io, "JuliaLang is a GitHub organization.", " It has many members.")
56

julia> String(take!(io))
"JuliaLang is a GitHub organization. It has many members."

julia> write(io, "Sometimes those members") + write(io, " write documentation.")
44

julia> String(take!(io))
"Sometimes those members write documentation."

當包裝在 Ref 中時,可以編寫沒有 write 方法的用戶定義的 plain-data 類型:

julia> struct MyStruct; x::Float64; end

julia> io = IOBuffer()
IOBuffer(data=UInt8[...], readable=true, writable=true, seekable=true, append=false, size=0, maxsize=Inf, ptr=1, mark=-1)

julia> write(io, Ref(MyStruct(42.0)))
8

julia> seekstart(io); read!(io, Ref(MyStruct(NaN)))
Base.RefValue{MyStruct}(MyStruct(42.0))

相關用法


注:本文由純淨天空篩選整理自julialang.org 大神的英文原創作品 Base.write — Function。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。