Skip to content

Struct std::fs::OpenOptions

可用于配置文件打开方式的选项和标志。

此构建器提供了配置 File打开方式以及打开的文件上允许哪些操作的功能

File::openFile::create 方法是使用此构建器的常用选项的别名。

一般而言,使用 OpenOptions 时,首先要调用 OpenOptions::new,然后链式调用方法以设置每个选项,然后调用 OpenOptions::open,传递要打开的文件的路径。

这将为您提供一个内部带有 Fileio::Result,您可以对其进行进一步的操作。

1.Examples

打开一个文件以读取:

rust
use std::fs::OpenOptions;

let file = OpenOptions::new().read(true).open("foo.txt");

打开一个文件进行读写,如果不存在则创建一个文件:

rust
use std::fs::OpenOptions;

let file = OpenOptions::new()
            .read(true)
            .write(true)
            .create(true)
            .open("foo.txt");

2.Implementations

impl OpenOptions

new

创建一组可供配置的空白新选项。所有选项最初都设置为 false

rust
pub fn new() -> Self

返回值:返回自身

rust
use std::fs::OpenOptions;

let mut options = OpenOptions::new();
let file = options.read(true).open("foo.txt");

read

设置读取访问权限的选项。

该选项为 true 时,则表示打开的文件应该是可读的。

rust
pub fn read(&mut self, read: bool) -> &mut Self

参数

  • read:设置打开的文件是否可读

返回值:返回自身

rust
use std::fs::OpenOptions;

let file = OpenOptions::new().read(true).open("foo.txt");

write

设置写访问权限的选项。

此选项为 true 时,则表示打开的文件应该是可写的。

如果该文件已经存在,则对该文件的任何写调用都将覆盖其内容,而不会将其截断。

rust
pub fn write(&mut self, write: bool) -> &mut Self

参数

  • write:设置打开的文件是否可写

返回值:返回自身

rust
use std::fs::OpenOptions;

let file = OpenOptions::new().write(true).open("foo.txt");

append

设置追加模式的选项。

此选项为 true 时,表示写入将追加到文件中,而不是覆盖以前的内容。

rust
pub fn append(&mut self, append: bool) -> &mut Self

参数

  • append
    • true:写入内容时,是从文件的末尾追加内容
    • false:写入内容时,是覆盖文件的原内容

返回值:返回自身

rust
use std::fs::OpenOptions;

let file = OpenOptions::new().append(true).open("foo.txt");

TIP

请注意,设置 .write(true).append(true) 与仅设置 .append(true) 具有相同的效果。

对于大多数文件系统,操作系统保证所有写操作都是原子的:不会浪费任何写操作,因为另一个进程会同时进行写操作。

使用追加模式时,可能有一个明显的注意事项:确保一次完成将所有在一起的数据写入文件。 这可以通过在将字符串传递给 write() 之前串联字符串,或使用缓冲的 writer (具有足够大小的缓冲区) 并在消息完成后调用 flush() 来完成。

如果同时使用读取和追加的访问权限打开文件,请注意,在打开之后以及每次写入之后,读取位置可能设置在文件末尾。 所以,在写入之前,保存当前位置 (使用 seek(SeekFrom::Current(0))),并在下次读取之前恢复它。

Note

如果该函数不存在,则该函数不会创建该文件。使用 OpenOptions::create 方法来执行此操作。

truncate

是否截断(清空)打开的文件

该文件必须具有写访问权限write(true)才能打开,才能进行截断。

rust
pub fn truncate(&mut self, truncate: bool) -> &mut Self

参数

  • truncate:是否清空打开的文件
    • 如果参数为true,则打开的文件内容会先被清空
    • 如果参数为false,则需要配合create(true)打开文件,否则会报错

返回值:返回自身

当有目标文件时,调用后文件内容会被清空

rust
use std::fs::OpenOptions;

fn main() {
    let file = OpenOptions::new()
        .write(true)
        .truncate(true)
        .open("test.txt");

    println!("{:#?}", file)
}

当目标文件不存在时,需要同时使用create(true)

rust
use std::fs::OpenOptions;

fn main() {
    let file = OpenOptions::new()
        .write(true)
        .create(true)
        .truncate(true)
        .open("test.txt");

    println!("{:#?}", file)
}

create

设置是否创建一个新文件,如果存在则将其打开

为了创建文件,必须使用write(true)append(true)方法设置文件可写

rust
pub fn create(&mut self, create: bool) -> &mut Self

参数

  • create:设置是否创建一个新文件

返回值:返回自身

rust
use std::fs::OpenOptions;

let file = OpenOptions::new().write(true).create(true).open("foo.txt");

create_new

设置创建新文件的选项,如果该文件已经存在则失败。

必须使用写或追加访问权限打开文件才能创建新文件。

rust
pub fn create_new(&mut self, create_new: bool) -> &mut Self

参数

  • create_new:是否创建新文件

返回值:返回自身

rust
use std::fs::OpenOptions;

let file = OpenOptions::new().write(true)
                             .create_new(true)
                             .open("foo.txt");

TIP

目标位置不允许存在任何文件,(dangling) 符号链接也不允许存在。这样,如果调用成功,则保证返回的文件是新文件。

此选项很有用,因为它是原子的。 否则,在检查文件是否存在与创建新文件之间,文件可能是由另一个进程创建的 (TOCTOU 竞态条件 / 攻击)。

如果设置了 .create_new(true),则忽略 .create().truncate()

open

使用 self 指定的选项在 path 打开文件。

rust
pub fn open<P: AsRef<Path>>(&self, path: P) -> Result<File>

参数

  • path:打开文件的路径

返回值:返回一个File文件对象,包裹在Result

rust
use std::fs::OpenOptions;

let file = OpenOptions::new().read(true).open("foo.txt");

Errors

在许多不同的情况下,此函数将返回错误。其中列出了一些错误条件及其 io::ErrorKind。 映射到 io::ErrorKind 不是函数兼容性契约的一部分。

  • NotFound: 指定的文件不存在,并且未设置 createcreate_new
  • AlreadyExists: 指定了 create_new 并且文件已经存在。
  • InvalidInput: 打开选项无效组合 (在没有写访问、没有访问模式设置等情况下截断)。

以下错误目前与任何现有的 io::ErrorKind 都不匹配:

  • 实际上,指定文件路径的目录组件之一不是目录。
  • 文件系统级错误:已满磁盘,对只读文件系统请求的写许可权,超出磁盘配额,打开的文件过多,文件名太长,指定路径中的符号链接太多 (仅适用于 Unix 系统),等等。

3.Trait Implementations

impl Clone for OpenOptions

clone

返回值的副本。

rust
fn clone(&self) -> OpenOptions

clone_from

把另一个对象上的属性克隆到自己身上

rust
fn clone_from(&mut self, source: &Self)

impl Debug for OpenOptions

fmt

使用给定的格式化程序格式化该值。

rust
fn fmt(&self, f: &mut Formatter<'_>) -> Result

impl OpenOptionsExt for OpenOptions

TIP

仅在WASI端可使用

lookup_flags

将自定义 dirflags 参数传递给 path_open。

rust
fn lookup_flags(&mut self, flags: u32) -> &mut OpenOptions

directory

指示 OpenOptions 是否必须打开目录。

rust
fn directory(&mut self, dir: bool) -> &mut OpenOptions

dsync

指示是否在 path_open 的 fs_flags 字段中传递 __WASI_FDFLAG_DSYNC。

rust
fn dsync(&mut self, enabled: bool) -> &mut OpenOptions

nonblock

指示是否在 path_open 的 fs_flags 字段中传递 __WASI_FDFLAG_NONBLOCK。

rust
fn nonblock(&mut self, enabled: bool) -> &mut OpenOptions

rsync

指示是否在 path_open 的 fs_flags 字段中传递 __WASI_FDFLAG_RSYNC。

rust
fn rsync(&mut self, enabled: bool) -> &mut OpenOptions

sync

指示是否在 path_open 的 fs_flags 字段中传递 __WASI_FDFLAG_SYNC。

rust
fn sync(&mut self, enabled: bool) -> &mut OpenOptions

fs_rights_base

指示应为 path_open 的 fs_rights_base 参数传递的值。

rust
fn fs_rights_base(&mut self, rights: u64) -> &mut OpenOptions

fs_rights_inheriting

指示应为 path_open 的 fs_rights_inheriting 参数传递的值。

rust
fn fs_rights_inheriting(&mut self, rights: u64) -> &mut OpenOptions

open_at

打开文件或目录

rust
fn open_at<P: AsRef<Path>>(&self, file: &File, path: P) -> Result<File>

impl OpenOptionsExt for OpenOptions

TIP

仅在Windows端可使用

access_mode

将 dwDesiredAccess 参数覆盖为具有指定值的 CreateFile。

rust
fn access_mode(&mut self, access: u32) -> &mut OpenOptions

share_mode

将 dwShareMode 参数覆盖为具有指定值的 CreateFile。

rust
fn share_mode(&mut self, share: u32) -> &mut OpenOptions

custom_flags

将 dwFileFlags 参数的额外标志设置为 CreateFile2 的指定值 (或将其与 attributes 和 security_qos_flags 组合以将 dwFlagsAndAttributes 设置为 CreateFile)。

rust
fn custom_flags(&mut self, flags: u32) -> &mut OpenOptions

attributes

将 dwFileAttributes 参数设置为 CreateFile2 的指定值 (或将其与 custom_flags 和 security_qos_flags 组合以将 dwFlagsAndAttributes 设置为 CreateFile)。

rust
fn attributes(&mut self, attributes: u32) -> &mut OpenOptions

security_qos_flags

将 dwSecurityQosFlags 参数设置为 CreateFile2 的指定值 (或将其与 custom_flags 和 attributes 组合以将 dwFlagsAndAttributes 设置为 CreateFile)。

rust
fn security_qos_flags(&mut self, flags: u32) -> &mut OpenOptions

impl OpenOptionsExt for OpenOptions

TIP

仅在Unix端可使用

mode

设置将用于创建新文件的模式位。

rust
fn mode(&mut self, mode: u32) -> &mut OpenOptions

custom_flags

将自定义标志传递给 open 的 flags 参数。

rust
fn custom_flags(&mut self, flags: i32) -> &mut OpenOptions

4.Auto Trait Implementations

impl RefUnwindSafe for OpenOptions

impl Send for OpenOptions

impl Sync for OpenOptions

impl Unpin for OpenOptions

impl UnwindSafe for OpenOptions

5.Blanket Implementations

impl<T> Any for T

rust
impl<T> Any for T
where
  T: 'static + ?Sized,

impl<T> Borrow<T> for T

rust
impl<T> Borrow<T> for T
where
  T: ?Sized,

impl<T> BorrowMut<T> for T

rust
impl<T> BorrowMut<T> for T
where
  T: ?Sized,

impl<T> From<T> for T

rust
impl<T> From<T> for T

impl<T, U> Into<U> for T

rust
impl<T, U> Into<U> for T
where
  U: From<T>,

impl<T> ToOwned for T

rust
impl<T> ToOwned for T
where
  T: Clone,

impl<T, U> TryFrom<U> for T

rust
impl<T, U> TryFrom<U> for T
where
  U: Into<T>,

impl<T, U> TryInto<U> for T

rust
impl<T, U> TryInto<U> for T
where
  U: TryFrom<T>,

MIT Licensed