我可以用Rust写二进制代码到文件。 但是,当我创建文件时,创建的文件是文本文件,而不是二进制文件。 我可以用这样的C ++创建一个二进制文件:
ofstream is("1.in", ofstream::binary | ofstream::out | ofstream:: trunc);
在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
);
}
运行此代码后,它会将200 u32整数二进制数写入文件tableIndexName
。 但是,文件大小不是800字节。 大约是4KB。
Rust的std::fs::File
没有以文本或二进制模式打开文件的概念。 所有文件都作为“二进制”文件打开,并且不执行换行和回车等字符的转换。
你的问题源于使用write!
宏。 此宏用于将数据格式化为可打印格式,如果要编写二进制数据,则不应使用此宏。 事实上,您使用的{:b}
格式说明符会将值转换为ASCII 1
和0
字符的可打印二进制字符串。
相反,使用trait std::io::Write
提供的函数。 此特征由File
直接实现,或者您可以使用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(())
}