我正在尝试将数字写入文件。我不想将文件中的数字表示为UFT-8或其他某种编码。我只想要写入文件的数字的二进制表示形式。
代码尝试写入文件,然后将文件读回用户。
use std::fs::File;
use std::io::prelude::*;
fn main() -> () {
let number:usize =244128131191;
let mut file = File::create("data").expect("create failed");
file.write_all(&[number]).expect("write failed");
println!("data written to file" );
let mut file = File::open("data").expect("open failed");
let mut buffer = Vec::<usize>::new();
file.read_to_end(&mut buffer);
println!("{:?}", buffer);
}
我回此错误,抱怨使用的类型。
Compiling writing_file v0.1.0 (file:///home/9716278/writing_file)
error[E0308]: mismatched types
--> src/main.rs:37:22
|
37 | file.write_all(&[number]).expect("write failed");
| ^^^^^^ expected u8, found usize
error[E0308]: mismatched types
--> src/main.rs:42:22
|
42 | file.read_to_end(&mut buffer);
| ^^^^^^^^^^^ expected u8, found usize
|
= note: expected type `&mut std::vec::Vec<u8>`
found type `&mut std::vec::Vec<usize>`
error: aborting due to 2 previous errors
error: Could not compile `counting_utf`.
To learn more, run the command again with --verbose.
我不确定出了什么问题。问题是与根据错误的类型有关。如果这是我要尝试的正确方法,我不是用户。
读取时文件的长度未知(因此将其读入没有固定长度的向量中,但是最后要使用的变量为usize类型。
我在这里显示了您可以将向量转换为固定大小的数组,然后将其转换为usize变量。
希望有人可以改善这个答案!
use std::fs::File;
use std::io::prelude::*;
fn main() -> () {
let number:usize = 244128131191;
// write number to file
let mut file = File::create("data").expect("create failed");
file.write_all(&number.to_ne_bytes()).expect("write failed");
println!("data written to file" );
// read file
let mut file = File::open("data").expect("open failed");
let mut buffer = Vec::<u8>::new();
file.read_to_end(&mut buffer);
//convert binary in vector back a variable of type usize
let mut arr = [0; 8]; //setup an empty array with 8 elements
arr.copy_from_slice(&buffer[0..buffer.len()]); //fill the fixed size array with the slice
let reading_of_number = usize::from_ne_bytes(arr); //convert the array to a variable of type usize
println!("{:?}", reading_of_number);
}
请注意使用to_ne_bytes()和from_ne_bytes()的结果。
如果文件要在一台机器上写入,然后在另一台机器上读取,那么您将根据需要使用to_be_bytes或to_le_bytes。但是,如果将始终在同一台计算机上写入和读取文件,那么这不成问题,您可以继续使用to_ne_bytes()和from_ne_bytes()-请参阅文档https://doc.rust-lang.org/std/primitive.u64.html#method.to_ne_bytes
感谢@ user2722968建议我以理解be / le / ne的重要性来改善答案。