gpt4 book ai didi

rust - 无法立即解码使用 bincode 写入文件的对象

转载 作者:行者123 更新时间:2023-11-29 08:01:40 34 4
gpt4 key购买 nike

当我尝试运行测试时出现此异常:

thread 'persistent_log::doc::test::test_sync' panicked at 'called `Result::unwrap()` on an `Err` value: IoError(Error { repr: Os { code: 9, message: "Bad file descriptor" } })', ../src/libcore/result.rs:783

期限:

#[derive(Copy, Clone, Debug, Hash, PartialEq, Eq, PartialOrd, Ord,RustcEncodable,RustcDecodable)]
pub struct Term(u64);

测试:

fn create() {
File::create(&"term");
}

#[test]
fn test_sync() {
create();

let mut f = File::open(&"term").unwrap();

let term = Term(10);

encode_into(&term, &mut f, SizeLimit::Infinite).unwrap();

let decoded_term: Term = decode_from(&mut f, SizeLimit::Infinite).unwrap();

assert_eq!(decoded_term, term);
}

我想将对象 term 写入一个文件,然后再读入。

最佳答案

File::open以只读模式打开文件,因此写入文件会失败。

要打开具有读写权限的文件,您必须使用 OpenOptions .

use std::fs::OpenOptions;

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

Great, but now I get a new exception:

thread 'persistent_log::doc::test::test_sync' panicked at 'called Result::unwrap() on an Err value: IoError(Error { repr: Custom(Custom { kind: UnexpectedEof, error: StringError("failed to fill whole buffer") }) })', ../src/libcore/result.rs:783

将字节写入文件后,文件的光标将位于文件末尾。在尝试读取文件之前,您必须 seek回到文件的开头,否则你会得到这个错误。

file.seek(SeekFrom::Start(0));

关于rust - 无法立即解码使用 bincode 写入文件的对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39436571/

34 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com