Working with files
To work with files, we need the IOStream type. IOStream is a type with the IO supertype and has the following characteristics:
- The fields are given by
fieldnames(IOStream):
(:handle, :ios, :name, :mark)
- The types are given by
IOStream.types:
(Ptr{Nothing}, Array{UInt8,1}, AbstractString, Int64)The file handle is a pointer of the Ptr type, which is a reference to the file object.
Opening and reading a line-oriented file with the example.dat name is very easy:
// code in Chapter 8\io.jl
fname = "example.dat"
f1 = open(fname) fname is a string that contains the path to the file, using the escaping of special characters with \ when necessary. For example, in Windows, when the file is in the test folder on the D: drive, this would become d:\\test\\example.dat. The f1 variable is now an IOStream(<file example.dat>) object.
To read all lines one after another in an array, use data = readlines(f1), which returns 3-element Array{String,1}:
"this is line 1." "42; 3.14" "this is...