gpt4 book ai didi

file - 如何将二进制数写入文件并在 Rust 中检索它

转载 作者:行者123 更新时间:2023-11-29 08:30:54 25 4
gpt4 key购买 nike

我正在尝试将数字写入文件。我不想将文件中的数字表示为 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 的重要性改进答案。

关于file - 如何将二进制数写入文件并在 Rust 中检索它,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58148885/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com