![](/img/trans.png)
[英]Reading exact number of bytes from file after writing object to it with bincode serialisation
[英]Cannot immediately decode an object written to a file with bincode
當我嘗試運行測試時,我收到此異常:
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");
很好,但現在我得到一個新的例外:
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
在將字節寫入文件后,文件的光標將位於文件的末尾。 您嘗試從文件中讀取之前,你必須設法回到文件的開始,否則你會得到這個錯誤。
file.seek(SeekFrom::Start(0));
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.