Working with files in tokio

I have some async code using tokio. I have vector of files which I need to copy. Tokio provides convenient way to asynchronously copy file with tokio::fs::copy. So now I have this code:

struct MyFile {
    filename: PathBuf,
    filesize: Option<i64>,
}

for f in files {
    let mut dest_file = dest_dir.clone();
    if let Some(name) = f.filename.file_name() {
        dest_file.push(name);
        tokio::fs::copy(f.filename, dest_file).await?;
    }
}

This works fine but in fact I need to copy only specified number of bytes started from the beginning of each file (MyFile::filesize field). So I need to open source file, read filesize number of bytes, write those bytes to destination file. It seems tokio::fs does not provide tools to do this. What should I do in this situation? Should I just fallback to regular (non async) file IO?

You can do this with tokio::fs::File.

Using regular non-async file IO is also an acceptable approach, but you must make sure to properly use spawn_blocking as described in Async: What is blocking?

Thank you Alice.
I will definitely read your blog post.

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.