rust - 是否可以使用相同的文件进行读写?

标签 rust

我正在尝试使用相同的 std::fs::File 对象进行写入和读取,但读取返回一个空字符串。

我尝试了 flushsync_allseek,但没有任何帮助。使用新的 File 对象,我可以轻松读取文件。

use std::io::{Read, Seek, Write};

const FILE_PATH: &str = "test.txt";

fn main() {
    // Create file
    let mut f = std::fs::File::create(FILE_PATH).unwrap();
    f.write_all("foo bar".as_bytes());
    f.seek(std::io::SeekFrom::Start(0));

    // Read from the same descriptor
    let mut content = String::new();
    f.read_to_string(&mut content);
    println!("{:?}", content); // -> ""

    // Read from the other descriptor
    let mut f = std::fs::File::open(FILE_PATH).unwrap();
    let mut content = String::new();
    f.read_to_string(&mut content);
    println!("{:?}", content); // -> "foo bar"
}

最佳答案

问题出在 File::createopens a file in write-only mode .解决方法是使用 std::fs::OpenOptions :

let mut f = std::fs::OpenOptions::new()
    .create(true)
    .write(true)
    .read(true)
    .open(FILE_PATH)
    .unwrap();

不要忘记使用 seek 重置阅读位置。

关于rust - 是否可以使用相同的文件进行读写?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47956653/

相关文章:

error-handling - 创建使用 try 运算符的闭包时如何修复错误 "type annotations needed"?

generics - Rust - 将泛型类型的泛型转化为 vec

rust - 传递给异步回调的引用的生命周期

rust - Rc 中用于 AST 操作的沮丧特征

Rust 如何从数组转换为 std::raw::Slice

rust - 如何检查用户输入的变量是数字(int,float)?

rust - Bencher.bytes是什么意思?

rust - 如何在 Rust 结构中同时更改两个字段?

rust - 为什么在放置的 Box 上使用 ptr::read() 不是未定义的行为?

iterator - 将迭代器 Item 类型不匹配解析为具有显式生命周期的指针