Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Bincode adds unexpected newline character to a file. #234

Closed
ghost opened this issue May 7, 2018 · 2 comments
Closed

Bincode adds unexpected newline character to a file. #234

ghost opened this issue May 7, 2018 · 2 comments

Comments

@ghost
Copy link

@ghost ghost commented May 7, 2018

I have following struct

struct Employee {
    id: u64,
    name: String,
}

I am serializing it with following code and then writing serialized byte array in a file:

let emp = Employee {
        id: 1546,
        name: "abcd".to_string(),
    };

    let mut file = OpenOptions::new()
        .read(true)
        .write(true)
        .create(true)
        .open("hello.txt")
        .unwrap();

    let initial_buf = &serialize(&emp).unwrap();

    println!("Initial Buf: {:?}", initial_buf);

    file.write(&serialize(&emp).unwrap());
    file.write(&[b'\n']);
    file.flush();

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

    let mut final_buf: Vec<u8> = Vec::new();

    let mut reader = BufReader::new(file);

    reader.read_until(b'\n', &mut final_buf).unwrap();

    println!("Final Buf: {:?}", final_buf);

I get the following output:

Initial Buf: [10, 6, 0, 0, 0, 0, 0, 0, 4, 0, 0, 0, 0, 0, 0, 0, 97, 98, 99, 100]
Final Buf: [10]

How can I add separators between different records in a file?

@dtolnay
Copy link
Collaborator

@dtolnay dtolnay commented May 7, 2018

@dtolnay dtolnay closed this May 7, 2018
@ghost
Copy link
Author

@ghost ghost commented May 8, 2018

Thanks @dtolnay
I wasn't aware that Rust community is so active on StackOverflow. That's the reason I posted at both places.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Linked pull requests

Successfully merging a pull request may close this issue.

None yet
1 participant
You can’t perform that action at this time.