file - 如何使用 Rust 创建二进制文件?

标签 file rust binaryfiles

我可以使用 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} format specifier您使用过的会将值转换为 ASCII 10 字符的可打印二进制字符串。

相反,使用 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(())
}

关于file - 如何使用 Rust 创建二进制文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53826371/

相关文章:

javascript - Edge 中的 &lt;input type ="file"> 无法识别输入事件

vector - 在 Rust 中连接向量的最佳方法是什么?

c# - BinaryWriter 不写入文件

python - Go build不会从脾气暴躁的生成Go代码生成二进制文件吗?

c# - C#中如何根据RegEx查找文件

windows - 对于 Windows,一个命令行 bat 文件,显示目录中每个文件的总行数

rust - 移入封闭的结构从外部借用了引用

struct - 如何克隆存储盒装特征对象的结构?

c++ - C++读取二进制文件

在 C 中关闭文件描述符(或套接字)