Loading search index…
No recent searches
No results for "Query here"
Reading and writing files are basic tasks needed for many Julia programs. First we’ll look at some examples of reading files.
using Printf # Reading files requires checking most calls for errors. # This helper will streamline our error checks below. function check(e) if e !== nothing error(e) end end # Perhaps the most basic file reading task is # slurping a file's entire contents into memory. dat = read("/tmp/dat", String) print(dat) # You'll often want more control over how and what # parts of a file are read. For these tasks, start # by opening a file to obtain an IOStream value. f = open("/tmp/dat") # Read some bytes from the beginning of the file. # Allow up to 5 to be read but also note how many # actually were read. b1 = Vector{UInt8}(undef, 5) n1 = readbytes!(f, b1) @printf("%d bytes: %s\n", n1, String(b1[1:n1])) # You can also seek to a known location in the file # and read from there. seek(f, 6) b2 = Vector{UInt8}(undef, 2) n2 = readbytes!(f, b2) @printf("%d bytes @ %d: ", n2, position(f) - n2) @printf("%s\n", String(b2[1:n2])) # Other methods of seeking are relative to the # current cursor position, skip(f, 4) # and relative to the end of the file. seekend(f) skip(f, -10) # The Base package provides some functions that may # be helpful for file reading. For example, reads # like the ones above can be more robustly # implemented with read!. seek(f, 6) b3 = Vector{UInt8}(undef, 2) n3 = read!(f, b3) @printf("%d bytes @ %d: %s\n", n3, position(f) - n3, String(b3)) # There is no built-in rewind, but # seek(f, 0) accomplishes this. seek(f, 0) # The Base package implements a buffered # reader that may be useful both for its efficiency # with many small reads and because of the additional # reading methods it provides. r4 = IOBuffer(read(f)) b4 = Base.peek(r4, UInt8, 5) @printf("5 bytes: %s\n", String(b4)) # Close the file when you're done (usually this would # be scheduled immediately after opening with # try/finally or do block). close(f)
To run the program:
$ echo "hello" > /tmp/dat $ echo "julia" >> /tmp/dat $ julia reading-files.jl hello julia 5 bytes: hello 2 bytes @ 6: ju 2 bytes @ 6: ju 5 bytes: hello
Next we’ll look at writing files.