【问题标题】:How do I open a file with the flags provided as an i32 matching the C open function?如何使用与 C open 函数匹配的 i32 提供的标志打开文件?
【发布时间】:2019-10-08 23:16:19
【问题描述】:

我需要打开一个文件,我有一个 &Path 和一个 i32 用于标志。我可以使用File::open(path) 打开文件,但这不会让我设置选项。文档说我应该使用OpenOptions,但我看不出有任何方法可以从我的i32 获得OpenOptions。我的标志的内容在open(2)中定义。

我使用的标志是526338,如果你想自己测试的话。

【问题讨论】:

  • 你从哪里得到i32?例如,它是否可以包含特定于操作系统的标志,或者只是可移植的 open(3p) 标志?
  • @Ry- 我从一些奇怪的库包装器中得到它。

标签: rust libc


【解决方案1】:

假设你在一个类 Unix 系统上,你可以使用OpenOptionsExt 来设置你的标志:

use std::fs::OpenOptions;
use std::os::unix::fs::OpenOptionsExt;

let file = OpenOptions::new()
    .read(true)
    .custom_flags(flags)
    .open(&path)?;

请注意,您必须单独设置访问模式标志(例如,通过调用 readwrite),因此如果您需要它们,您必须自己处理它们。例如:

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)?;

【讨论】:

  • 当我这样做时,我得到Os { code: 22, kind: InvalidInput, message: "Invalid argument" }。我知道标志是正确的,因为当我使用相同的参数调用 libc::open 时,它可以工作
  • Sorry mode 用于访问模式,open(2) 的标志设置为 custom_flags。我会更新答案。
  • 如果你想自己测试的话,我使用的标志是526338。我已经尝试过custom_flags,但没有帮助。我也尝试了这两种方法(因为文档说有些东西被掩盖了,而另一些没有),但仍然是同样的错误。
  • 您需要调用readwrite 来设置访问模式(在这里测试:如果我不调用任何一个,即使没有custom_flags,我也会收到“无效参数”错误. 如果我打电话给.read (true) 那么它适用于.custom_flags (526338))。
猜你喜欢
  • 2010-10-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-11-26
  • 2012-03-06
  • 1970-01-01
  • 2015-06-14
  • 1970-01-01
相关资源
最近更新 更多