#How to avoid dead lock when writing to a file with tauri/rust

15 messages · Page 1 of 1 (latest)

pliant cipher
#

have this rust method in tauri

#[tauri::command]
async fn overwrite_file_content(path: String, new_content: String) -> Result<(), String> {
    use std::io::Write;

    let path = PathBuf::from(&path);
    if path.exists() {
        let mut file = match fs::OpenOptions::new().write(true).open(&path) {
            Ok(file) => file,
            Err(e) => return Err(format!("Failed to open file: {}", e)),
        };

        match file.write_all(new_content.as_bytes()) {
            Ok(_) => Ok(()),
            Err(e) => Err(format!("Failed to write to file: {}", e)),
        }
    } else {
        Err("File does not exist".into())
    }
}

for some reason after trying to write to any file, for example a file that ends with

- [Testing The "Impossible": 17 Questions That Changed My Life (2016)](https://tim.blog/2016/12/07/testing-the-impossible-17-questions-that-changed-my-life/)
- [The Proust Questionnaire](https://www.vanityfair.com/magazine/2000/01/proust-questionnaire)

after that rust method is called, the file will be

- [Testing The "Impossible": 17 Questions That Changed My Life (2016)](https://tim.blog/2016/12/07/testing-the-impossible-17-questions-that-changed-my-life/)
- [The Proust Questionnaire](https://www.vanityfair.com/magazine/2000/01/proust-questionnaire)
aire)

notice the aire) added.

i asked gpt-4 for a fix but solution it gave failed for me, how can I solve this? thanks ♥️

#
        await invoke("overwrite_file_content", {
          path: pathToFile,
          newContent: newFileContent,
        })
#

is how I invoke it

#

it does modify the file

#

for example that test should indeed be there but that last line should not be, no idea why it's even there

#

i pass this as string just now to that rust method

#

and it added this random )

#

something rust is doing thats odd

#

ok that seems to have worked

#

from my limited testing, if anyone reading this, has solution to better do this code, would be very happy

#
#[tauri::command]
async fn overwrite_file_content(path: String, new_content: String) -> Result<(), String> {
    use std::io::Write;

    let path = PathBuf::from(&path);
    if path.exists() {
        let mut file = match fs::OpenOptions::new()
            .write(true)
            .truncate(true)
            .open(&path)
        {
            Ok(file) => file,
            Err(e) => return Err(format!("Failed to open file: {}", e)),
        };

        match file.write_all(new_content.as_bytes()) {
            Ok(_) => Ok(()),
            Err(e) => Err(format!("Failed to write to file: {}", e)),
        }
    } else {
        Err("File does not exist".into())
    }
}

#

im newish at rust still

dense narwhal