【问题标题】:Unable to override temporary file with `tempfile`无法用“tempfile”覆盖临时文件
【发布时间】:2023-01-11 06:43:35
【问题描述】:

创建用于套接字使用的临时文件时出错:

Error: Custom { kind: AlreadyExists, error: PathError { path: "/tmp", err: Custom { kind: AlreadyExists, error: "too many temporary files exist" } } }

use tempfile::{tempfile, Builder, NamedTempFile};

#[tokio::main]
async fn main() -> Result<(), Box<dyn Error>> {
    let file = Builder::new().prefix("testsock").rand_bytes(0).tempfile()?;


    Ok(())
}

有什么办法可以覆盖该文件吗?

【问题讨论】:

  • 既然设置了rand_bytes (0),为什么还要用tempfiletempfile 的全部意义在于文件名的一部分是随机生成的。如果你想要一个固定的名字,直接使用File

标签: rust temporary-files rust-tokio


【解决方案1】:

如果它尝试创建的文件已经存在,则会出现 two many files exist 错误。您可以通过删除临时目录中的文件来解决此错误。在您的情况下,这可能在 /tmp/testsock/ 中,如果仅删除文件不起作用,您可能还需要删除文件夹 testsock。


如果.tempfile(),将使用默认临时文件

但是,如果您使用以下内容,则可以指定临时文件。

let tmp = Builder::new()
        .prefix("example")
        .rand_bytes(0)
        .tempfile_in("./")?;

可以找到临时文件生成器的文档: https://docs.rs/tempfile/latest/tempfile/struct.Builder.html

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-09-20
    • 2014-06-19
    • 2015-03-16
    相关资源
    最近更新 更多