如何使用与 C 打开函数匹配的 i32 提供的标志打开文件?
How do I open a file with the flags provided as an i32 matching the C open function?
我需要打开一个文件,我有一个 &Path
和一个 i32
作为标志。我可以使用 File::open(path)
打开文件,但这不会让我设置选项。文档说我应该使用 OpenOptions
,但我看不出有什么方法可以从我的 i32
中获取 OpenOptions
。我的标志的内容定义为 open(2)
.
我使用的标志是526338
,如果你想自己测试的话。
假设您使用的是类 Unix 系统,您可以使用 OpenOptionsExt
来设置您的标志:
use std::fs::OpenOptions;
use std::os::unix::fs::OpenOptionsExt;
let file = OpenOptions::new()
.read(true)
.custom_flags(flags)
.open(&path)?;
请注意,您必须单独设置访问模式标志(例如通过调用 read
或 write
),因此如果您需要它们,您将不得不自己处理它们。例如:
use std::os::unix::fs::OpenOptionsExt;
use libc::{O_RDONLY, O_RDWR, O_WRONLY};
let file = OpenOptions::new()
.custom_flags(flags)
.read((flags & O_ACCMODE == O_RDONLY) || (flags & O_ACCMODE == O_RDWR))
.write((flags & O_ACCMODE == O_WRONLY) || (flags & O_ACCMODE == O_RDWR))
.open(&path)?;
我需要打开一个文件,我有一个 &Path
和一个 i32
作为标志。我可以使用 File::open(path)
打开文件,但这不会让我设置选项。文档说我应该使用 OpenOptions
,但我看不出有什么方法可以从我的 i32
中获取 OpenOptions
。我的标志的内容定义为 open(2)
.
我使用的标志是526338
,如果你想自己测试的话。
假设您使用的是类 Unix 系统,您可以使用 OpenOptionsExt
来设置您的标志:
use std::fs::OpenOptions;
use std::os::unix::fs::OpenOptionsExt;
let file = OpenOptions::new()
.read(true)
.custom_flags(flags)
.open(&path)?;
请注意,您必须单独设置访问模式标志(例如通过调用 read
或 write
),因此如果您需要它们,您将不得不自己处理它们。例如:
use std::os::unix::fs::OpenOptionsExt;
use libc::{O_RDONLY, O_RDWR, O_WRONLY};
let file = OpenOptions::new()
.custom_flags(flags)
.read((flags & O_ACCMODE == O_RDONLY) || (flags & O_ACCMODE == O_RDWR))
.write((flags & O_ACCMODE == O_WRONLY) || (flags & O_ACCMODE == O_RDWR))
.open(&path)?;