Yen*_*Lee 2 binaryfiles file rust
我可以用Rust写二进制代码到文件.但是,当我创建文件时,创建的文件是文本文件,而不是二进制文件.我可以用这样的C++创建一个二进制文件:
ofstream is("1.in", ofstream::binary | ofstream::out | ofstream:: trunc);
Run Code Online (Sandbox Code Playgroud)
在Rust怎么样?这是我的尝试:
struct IndexDataStructureInt {
row: u32,
key_value: u32,
}
let mut index_arr: Vec<IndexDataStructureInt> = Vec::new();
// doing something push 100 IndexDataStructureInt to index_arr
let mut fileWrite = File::create(tableIndexName).unwrap();
for i in 0..index_arr.len() {
write!(
fileWrite,
"{:b}{:b}",
index_arr[i].row, index_arr[i].key_value
);
}
Run Code Online (Sandbox Code Playgroud)
运行此代码后,它会将200 u32整数二进制数写入文件tableIndexName.但是,文件大小不是800字节.大约是4KB.
har*_*mic 12
Rust std::fs::File没有在文本或二进制模式下打开文件的概念.所有文件都作为"二进制"文件打开,并且不执行换行和回车等字符的转换.
您的问题源于使用write!宏.此宏用于将数据格式化为可打印格式,如果要编写二进制数据,则不应使用此宏.实际上,您使用的{:b}格式说明符会将值转换为ASCII 1和0字符的可打印二进制字符串.
相反,使用trait提供的功能std::io::Write.此特征可以直接实现File,也可以使用a BufWriter来获得更好的性能.
例如:这里我write_all用来写一个u8文件片,然后read_to_end用来读回同一个文件Vec.
use std::fs::File;
use std::io::prelude::*;
fn main() -> std::io::Result<()> {
{
let mut file = File::create("test")?;
// Write a slice of bytes to the file
file.write_all(&[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15])?;
}
{
let mut file = File::open("test")?;
// read the same file back into a Vec of bytes
let mut buffer = Vec::<u8>::new();
file.read_to_end(&mut buffer)?;
println!("{:?}", buffer);
}
Ok(())
}
Run Code Online (Sandbox Code Playgroud)