Basic input and output

Julia's vision on input/output (I/O) is stream-oriented, that is, reading or writing streams of bytes. We will introduce different types of stream, file streams, in this chapter. Standard input (stdin) and standard output (stdout) are constants of the TTY type (an abbreviation for the old term, Teletype) that can be read from and written to in Julia code (refer to the code in Chapter 8io.jl):

  • read(stdin, Char): This command waits for a character to be entered, and then returns that character; for example, when you type in J, this returns 'J'
  • write(stdout, "Julia"): This command types out Julia5 (the added 5 is the number of bytes in the output stream; it is not added if the command ends in a semicolon ;)

stdin and stdout are simply streams and can be replaced by any stream object in read/write commands. readbytes is used to read a number of bytes from a stream into a vector:

  • read(stdin,3): This command waits for an input, for example, abe reads three bytes from it, and then returns 3-element Array{Uint8,1}: 0x61 0x62 0x65.
  • readline(stdin): This command reads all the input until a newline character,  , is entered. For example, type Julia and press Enter; this returns "Julia " on Windows and "Julia " on Linux.

If you need to read all the lines from an input stream, use the eachline method in a for loop, for example:

stream = stdin
for line in eachline(stream) println("Found $line") # process the line end

Include the following REPL dialog as an example:

First line of input
Found First line of input
2nd line of input
Found 2nd line of input
3rd line...
Found 3rd line...

To test whether you have reached the end of an input stream, use eof(stream) in combination with a while loop, as follows:

while !eof(stream) 
     x = read(stream, Char) 
     println("Found: $x")  
# process the character 
end 

We can experiment with the preceding code by replacing stream with stdin in these examples.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.145.35.247