readbytes

readbytes(stream, nb=typemax(Int); all=true)

Read at most nb bytes from the stream, returning a Vector{UInt8} of the bytes read.

If all is true (the default), this function will block repeatedly trying to read all requested bytes, until an error or end-of-file occurs. If all is false, at most one read call is performed, and the amount of data returned is device-dependent. Note that not all stream types support the all option.

Examples

  1. Read a fixed number of bytes from a file:

    julia> file = open("data.txt", "r");
    julia> bytes = readbytes(file, 10)
    10-element Array{UInt8,1}:
    0x48
    0x65
    0x6c
    0x6c
    0x6f
    0x20
    0x57
    0x6f
    0x72
    0x6c

    This example reads 10 bytes from the file "data.txt" and stores them in the bytes array.

  2. Read all available bytes from a network stream:

    julia> using Sockets
    julia> sock = connect("example.com", 80)
    julia> response = readbytes(sock)
    1461-element Array{UInt8,1}:
    0x48
    0x54
    0x54
    0x50
    0x2f
    0x31
    0x2e
    0x31
    0x20
    0x32
    0x30
    0x30
    0x20
    0x4f
    0x4b
    0x0d
    0x0a
    ⋮

    In this example, readbytes is used to read all available bytes from a network socket.

  3. Specify the maximum number of bytes to read:
    julia> file = open("data.txt", "r");
    julia> bytes = readbytes(file, 5; all=false)
    5-element Array{UInt8,1}:
    0x48
    0x65
    0x6c
    0x6c
    0x6f

    By setting all=false, only a single read call is made, and the function returns at most nb bytes.

Common mistake example:

julia> file = open("data.txt", "r");
julia> bytes = readbytes(file, -10)
ERROR: ArgumentError: number of bytes must be non-negative

In this example, a negative value is passed as the number of bytes to read. The number of bytes must be non-negative. Ensure that the nb argument is always a valid number of bytes to read.

See Also

deserialize, eachline, eof, fd, flush, IOBuffer, ismarked, isopen, isreadonly, mark, nb_available, open, pipeline, position, read, read!, readavailable, readbytes, readbytes!, readline, redirect_stderr, redirect_stdin, reset, seek, seekend, seekstart, serialize, skip, skipchars, TextDisplay, unmark, write, writemime,

User Contributed Notes

Add a Note

The format of note supported is markdown, use triple backtick to start and end a code block.

*Required Field
Details

Checking you are not a robot: