Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Open file in read-write mode in Rust [duplicate]

Tags:

file

rust

In Rust, how do I open a file for reading and writing? File::open() is read-only, and File::create() claims is write-only (and also creates files which isn't what I want).

like image 775
Timmmm Avatar asked Apr 26 '18 09:04

Timmmm


1 Answers

As of Rust 1.58 (the next release as I write this) you can do this:

use std::fs::File;

let mut file = File::options()
    .read(true)
    .write(true)
    .open("foo.txt")?;

On older versions you can use the OpenOptions struct to open the file. It's the same as the above code but a bit more weirdly named.

use std::fs::OpenOptions;

let mut file = OpenOptions::new()
    .read(true)
    .write(true)
    .open("foo.txt")?;
like image 113
Timmmm Avatar answered Oct 20 '22 11:10

Timmmm