# Read file to io

**URL:** https://discourse.julialang.org/t/read-file-to-io/102629
**Category:** General Usage
**Tags:** question
**Created:** [August 9, 2023, 10:48am UTC](https://discourse.julialang.org/t/read-file-to-io/102629 "2023-08-09T10:48:50Z")
**Posts on this page:** 2
**Page:** 1

<div class="post-metadata">

### Author: ![Tamas\_Papp](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/tamas_papp/32/25949_2.png) [@Tamas\_Papp](https://discourse.julialang.org/u/Tamas_Papp)
#### Post date: [August 9, 2023, 10:48am UTC](https://discourse.julialang.org/t/read-file-to-io/102629/1 "2023-08-09T10:48:50Z")

</div>

Given a filename and an `io::IO`, what’s the recommended way of reading a file and dumping it to `io`?

A naive solution is

```julia
function read_to_io(filename::AbstractString, io::IO)
    open(filename, "r") do src_io
        while !eof(src_io)
            write(io, read(src_io, UInt8))
        end
    end
end

```

but I am looking for something efficient. I could use a buffer as in

```julia
function read_to_io(filename::AbstractString, io::IO; bufsize = 2^12)
    buffer = Vector{UInt8}(undef, bufsize)
    open(filename, "r") do src_io
        while !eof(src_io)
            n = readbytes!(src_io, buffer, bufsize)
            write(io, @view buffer[1:n])
        end
    end
end

```

but I am not sure what the buffer size should be. Alternative solutions welcome.

---

<div class="post-metadata">

### Author: ![Sukera](https://avatars.discourse-cdn.com/v4/letter/s/ce7236/32.png) [@Sukera](https://discourse.julialang.org/u/Sukera)
#### Post date: [August 9, 2023, 12:04pm UTC](https://discourse.julialang.org/t/read-file-to-io/102629/2 "2023-08-09T12:04:44Z")

</div>

The optimal buffer size will depend on the read & write speeds of your disk, as well as whether you’re writing to a disk or the network in the first place. There’s no “one size fits all” here, but chunks in the size of a few megabytes (especially if everything is going off of a PCIe SSD) will likely still be performant.
