Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why am I getting a "bad file descriptor" error when writing file in rust?

Tags:

rust

Ignoring the fact that I'm using unwrap to ignore what happens if the file doesn't exist, it seems to me like this short bit of code should work (as long as the file does exist):

use std::fs::File;
use std::io::Write;

fn main() {
    let mut f = File::open("test.txt").unwrap();
    let result = f.write_all(b"some data");

    match result {
        Ok(_) => println!("Data written successfully"),
        Err(e) => panic!("Failed to write data: {}", {e}),
    }
}

Instead, I'm getting this:

thread 'main' panicked at 'Failed to write data: Bad file descriptor (os error 9)', src/main.rs:10:19

To be clear, I know if I follow one of the many examples online, I can write to a file. The question isn't "how do I write to a file?". It's why THIS isn't working.

like image 287
John Avatar asked Jan 23 '21 17:01

John


1 Answers

It isn't working because File::open() open's a file in read-only mode. Instead you have to use File::create() which opens a file in write-only mode. Alternatively you can also use OpenOptions, to further specify if you want to append() to a file instead.

use std::fs::File;
use std::io::Write;

fn main() {
    let mut f = File::create("test.txt").unwrap();

    let result = f.write_all(b"some data");

    match result {
        Ok(_) => println!("Data written successfully"),
        Err(err) => panic!("Failed to write data: {}", err),
    }
}

Using File::create() is the same as using OpenOptions in the following way:

use std::fs::OpenOptions;
use std::io::Write;

fn main() {
    let mut f = OpenOptions::new()
        .write(true)
        .create(true)
        .truncate(true)
        .open("test.txt")
        .unwrap();

    let result = f.write_all(b"some data");

    match result {
        Ok(_) => println!("Data written successfully"),
        Err(err) => panic!("Failed to write data: {}", err),
    }
}
like image 83
vallentin Avatar answered Sep 20 '22 00:09

vallentin