当我尝试运行测试时,我收到此异常:
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
Run Code Online (Sandbox Code Playgroud)
术语:
#[derive(Copy, Clone, Debug, Hash, PartialEq, Eq, PartialOrd, Ord,RustcEncodable,RustcDecodable)]
pub struct Term(u64);
Run Code Online (Sandbox Code Playgroud)
测试:
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);
}
Run Code Online (Sandbox Code Playgroud)
我想将对象term写入文件,然后将其读入.
Fra*_*gné 11
File::open 以只读模式打开文件,因此写入文件将失败.
要打开具有读写访问权限的文件,必须使用OpenOptions.
use std::fs::OpenOptions;
let file = OpenOptions::new()
.read(true)
.write(true)
.create(true)
.open("term");
Run Code Online (Sandbox Code Playgroud)
很好,但现在我得到一个新的例外:
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));
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
706 次 |
| 最近记录: |