I create a big size array name , and copy "Ross" to it, and then I want to write the name to file.
What I want is the file only combined with "Ross"
But now the file goes like this:
Ross^@^@^@^@^@^@^@^@^@^@^@^@
I didn't find a way to write only the first several words of the array.
I want an end character like '\0' in C so that only the meaningful words will be written.
Also, I don't know why ^@ appears in the file.
let mut name: [u8; 100] = unsafe {mem::zeroed()};
let s = "Ross";
let mut i = 0;
while i < s.len() {
name[i] = s.as_bytes()[i];
i += 1;
}
let mut file = File::create("name.test").expect("failed to open file");
file.write_all(&name).expect("failed to write file");
println!("name:{}", s);
How do you look into the file? ^@ is used by some editors to display a byte with value zero in a text file. Similar how ^M is used to display \r-bytes by vi.
If you have vi installed, you can use xxd to actually see a hex dump of your file (Some linux distributions have it in an extra vi-common package though).
let mut name: Vec = Vec::new();
let s = b"Ross";
name.extend_from_slice(s);
let mut file = File::create("name.test").expect("failed to open file");
file.write_all(&name).expect("failed to write file");
The use of Vec doesn't cost a lot for performance the code is I think more concise