You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Rust中将String写入文件报错‘Bad file descriptor’求助

Rust中String写入文件报错"Bad file descriptor (os error 9)"的解决方法

你的错误根源很明确:用只读模式打开的文件句柄执行了写入操作。File::open()默认以只读权限打开文件,后续调用write_all()必然失败,抛出"Bad file descriptor"错误。

另外你提到的String和&str写入文件的区别——其实两者本质完全一致,都是将字符串转成字节流写入,不存在String专属的特殊写法,只是你之前的文件打开逻辑错了。

修正方案

用std::fs::OpenOptions替代File::open(),灵活配置文件的读写权限和行为:

use std::fs::{File, OpenOptions};
use std::io::{self, Read, Write, Seek, SeekFrom};

fn main() {
    println!("Program started...");

    // 配置文件打开参数:可读、可写、不存在则创建、写入前清空原内容
    let mut testfile = OpenOptions::new()
        .read(true)
        .write(true)
        .create(true)
        .truncate(true)
        .open("/home/julian/.rust_test/test_0.txt")
        .unwrap();

    let mut teststring = String::from("lol");
    // 读取文件内容到字符串
    testfile.read_to_string(&mut teststring).unwrap();
    println!("teststring: {}", teststring);

    let msg = String::from("Writetest tralalalal.");
    teststring.push_str(&msg);
    println!("teststring: {}", teststring);

    // 读取后文件指针在末尾,移到开头以覆盖原内容(如果要追加可跳过此步,改用append(true)模式)
    testfile.seek(SeekFrom::Start(0)).unwrap();
    // 写入字符串(String转字节流和&str完全一致)
    match testfile.write_all(teststring.as_bytes()) {
        Ok(()) => println!("OK"),
        Err(e) => println!("{}", e)
    }    
    println!("Fertig")
}

关键说明

  • OpenOptions的参数可按需调整:
    • 如果只想追加内容而非覆盖,把truncate(true)换成append(true),同时可以省略seek步骤
    • 如果文件一定存在,可去掉create(true)
  • String写入文件的核心是调用as_bytes()转成字节切片,这和&str的写法完全相同,不存在专门针对String的特殊API

内容的提问来源于stack exchange,提问作者Jman_03

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.21 04:36:13