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

Rust程序用File::open写入文件时遇PermissionDenied错误的解决方法

权限拒绝错误:Rust程序无法写入目标文件

我编写的Rust程序旨在读取模板文件内容,并将其应用到目录中所有以}B开头的文件。程序可在IDE和终端(cargo run)中正常编译,但运行时出现错误:

Couldn't write file: Os { code: 5, kind: PermissionDenied, message: "access denied" }

错误发生在apply_template函数的file.write_all()行。

Cargo.toml 内容

[package]
name = "insert_text"
version = "0.1.0"
edition = "2021"

# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html

[dependencies]
regex = "1.7.2"

main.rs 核心代码

use std::fs;
use std::io;
use std::path::Path;
use std::fs::File;
use regex::Regex;

fn main() {
    let template = read_template();
    apply_template(&template);
}

fn get_user_input(what_input: &str) -> String{
    println!("Please enter the Path where {} is.", what_input);
    let mut user_input = String::new();
    io::stdin().read_line(&mut user_input).expect("Not a Valid Input");
    return user_input;
}

fn read_template() -> String{
    let user_input = get_user_input("template");
    let mut path = Path::new(&user_input);
    let mut file = match fs::File::open(path) {
        Ok(file) => file,
        Err(why) => { panic!("couldn't open: {}", why)}
    };
    let mut template_content = String::new();
    match file.read_to_string(&mut template_content){
        Ok(_) => println!("Successfully read template"),
        Err(why) => {println!("Couldn't convert file to template: {}", why)},
    }
    return template_content;

}

fn apply_template(template : &str) {
    //let mut user_input = get_user_input("Folder");
    let mut path_to_folder = Path::new("C:/Users/micrs/Documents/Neuer Ordner/");
    let files = fs::read_dir(path_to_folder).unwrap();

    let re = Regex::new(r"}B.*").unwrap();
    for file in files{
        if re.is_match(&file.as_ref().unwrap().file_name().to_str().unwrap()){
            let file_path = file.unwrap().path();

            let mut file = File::open(file_path).expect("Couldn't find file");
            file.write_all(template.as_bytes()).expect("Couldn't write file");


        }
    }
    println!("Successfully changed files.")
}

我已尝试以下操作:

  • 检查文件属性,确认具备写入权限
  • 在管理员控制台运行cargo run,但仍出现相同错误

请问如何让该程序成功写入目标文件?


问题根源与修复方案

1. 文件打开模式错误

你当前使用File::open()打开文件,该方法默认是只读模式,因此调用write_all()必然触发权限拒绝错误。需要改用支持写入的打开方式:

  • 若要覆盖文件原有内容,使用File::create():
let mut file = File::create(file_path).expect("Couldn't create file for writing");
  • 若要在文件末尾追加内容,或保留原有内容写入,使用OpenOptions自定义模式:
use std::fs::OpenOptions;

// 追加模式
let mut file = OpenOptions::new()
    .write(true)
    .append(true)
    .open(file_path)
    .expect("Couldn't open file for appending");

// 覆盖模式(效果与create类似,可额外配置参数)
let mut file = OpenOptions::new()
    .write(true)
    .truncate(true)
    .create(true)
    .open(file_path)
    .expect("Couldn't open file for writing");

2. 其他潜在问题排查

  • 文件被占用:目标文件可能被其他程序(如编辑器、杀毒软件)锁定,关闭相关程序后重试。
  • 路径换行符问题:get_user_input()中read_line()会读取输入的换行符,导致路径无效,需用.trim()清理:
fn get_user_input(what_input: &str) -> String{
    println!("Please enter the Path where {} is.", what_input);
    let mut user_input = String::new();
    io::stdin().read_line(&mut user_input).expect("Not a Valid Input");
    // 移除首尾空白(含换行符)
    user_input.trim().to_string()
}
  • 目录权限限制:Windows下Documents等系统目录可能有特殊权限控制,尝试将目标文件夹移至非系统目录(如D:/test)测试。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.27 14:22:43