-1

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")
}
Herohtar
  • 5,347
  • 4
  • 31
  • 41
Jman_03
  • 13
  • 3
  • Sadly not really. I read it before. It gets on the Question with the &str/ String problem(I think i overread it), but it doesn't have an explanation for the OS error. – Jman_03 Aug 26 '22 at 19:23
  • You need to include the full error printout from the console, not just the error message description. – Herohtar Aug 26 '22 at 19:33
  • To add to @Herohtar: You should add the full output of `cargo check`. – Finomnis Aug 26 '22 at 19:34
  • 2
    Also pay attention to the [`File::open()`](https://doc.rust-lang.org/std/fs/struct.File.html#method.open) documentation. Note that it opens the file in *read-only* mode. – Herohtar Aug 26 '22 at 19:35

1 Answers1

0

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.

Finomnis
  • 18,094
  • 1
  • 20
  • 27
  • @Jman_03 Additionally, I just wanted to add: Don't worry about types too much. Rust won't let you mis-use types. If it compiles, it works. You can't accidentally cause errors by forgetting a `&` somewhere. In Rust, all of those things are compile time errors, not runtime errors. – Finomnis Aug 26 '22 at 19:56