Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to write a String to file?

I am very new to Rust, and have the question, how to write a string to a file in Rust. There are plenty of tutorials and documentations out there, how to write an &str type to file, but no tutorial how to write a String type to files. I wrote this code by myself and it compiles, but I always get an "Bad file descriptor (os error 9)". I’m on Linux(Manjaro).
I’m very thankfully for every help I will get.

//Import
use std::fs::File;
use std::io::*;


//Mainfunction
fn main() {
    //Programm startet hier | program starts here
    println!("Program started...");
    
    // Lesen des Files, createn des Buffers | reading file createing buffer 
    let mut testfile = File::open("/home/julian/.rust_test/test_0.txt").unwrap();
    let mut teststring = String::from("lol");
    
    //Vom File auf den Buffer schreiben | writing from file to buffer
    testfile.read_to_string(&mut teststring).unwrap();
    
    //Buffer ausgeben | print to buffer
    println!("teststring: {}", teststring);
    
    // Neue Variable deklarieren | declare new variable
    let msg = String::from("Writetest tralalalal.");
    
    // msg an ursprünglichen String anhängen | append msg to string
    teststring.push_str(&msg);
    println!("teststring: {}", teststring);
    
    // Neuen String nach File schreiben | write new sting to file
    let eg = testfile.write_all(&teststring.as_bytes());
    match eg {
    Ok(()) => println!("OK"),
    Err(e) => println!("{}",e)

    }    
    println!("Fertig")
}

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Your issue is that the file you opened is opened in read-only mode.

As @Herohtar correctly pointed out, from the documentation of File::open():

Attempts to open a file in read-only mode.

What you are trying to do requires read & write mode. There is no pre-made function for that, so you need to build your own using OpenOptions:

//Import
use std::fs::OpenOptions;
use std::io::*;

//Mainfunction
fn main() {
    //Programm startet hier | program starts here
    println!("Program started...");

    // Lesen des Files, createn des Buffers | reading file createing buffer
    let mut testfile = OpenOptions::new()
        .read(true)
        .write(true)
        .open("test_0.txt")
        .unwrap();
    let mut teststring = String::from("lol");

    //Vom File auf den Buffer schreiben | writing from file to buffer
    testfile.read_to_string(&mut teststring).unwrap();

    //Buffer ausgeben | print to buffer
    println!("teststring: {}", teststring);

    // Neue Variable deklarieren | declare new variable
    let msg = String::from("Writetest tralalalal.");

    // msg an ursprünglichen String anhängen | append msg to string
    teststring.push_str(&msg);
    println!("teststring: {}", teststring);

    // Neuen String nach File schreiben | write new sting to file
    let eg = testfile.write_all(teststring.as_bytes());
    match eg {
        Ok(()) => println!("OK"),
        Err(e) => println!("{:?}", e),
    }
    println!("Fertig")
}

The rest of your code is pretty much fine.

The only nitpick I have is that testfile.write_all(&teststring.as_bytes()) doesn’t make much sense, because as_bytes() already returns a reference, so I removed the & from it.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading