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

时间:2016-09-11 13:24:16

标签: rust

当我尝试运行测试时,我收到此异常:

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写入文件,然后将其读入。

1 个答案:

答案 0 :(得分:11)

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

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

public ActionResult ViewAllResponse()
        {
            var responses = new List<Response>();
            using (ACIFYPJEntities aci = new ACIFYPJEntities())
            {
                responses = aci.Responses.ToList();
            }
            return View(responses);
        }


        public ActionResult ResponseFeedBack(int responseID)
        {
            var responses = new List<Response>();

            using (ACIFYPJEntities aci = new ACIFYPJEntities())
            {
                responses = (from c in aci.Responses
                             where c.responseID == responseID
                             select c).ToList();
            }

            return View(responses);
        }
  

很好,但现在我得到了一个新例外:

     

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

在您向文件写入字节后,文件的光标将位于文件的末尾。在您尝试从文件中读取之前,您必须seek返回文件的开头,否则您将收到此错误。

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