如何写入大于 2 GB 的文件?

How to write files larger than 2 GB?

以下代码:

use std::fs::File;
use std::io::Write;

fn main() {
    let encoded: Vec<u8> = vec![0; 2500000000];
    let mut buffer = File::create("file.bin").unwrap();
    let written_bytes = buffer.write(&encoded).unwrap();
    assert_eq!(written_bytes, encoded.len());
}

错误:

thread 'main' panicked at 'assertion failed: `(left == right)`
  left: `2147479552`,
 right: `2500000000`', src/main.rs:8:5

所以似乎有 2^31 - 4096 字节的限制。

我该如何解决这个问题?我想写一个更大的文件。 :)

Rusts write 依赖底层 OS 来写入字节。

对于 Linux 系统,将使用 write syscall

According to POSIX.1, if count is greater than SSIZE_MAX, the result is implementation-defined; see NOTES for the upper limit on Linux.

备注:

On Linux, write() (and similar system calls) will transfer at most 0x7ffff000 (2,147,479,552) bytes, returning the number of bytes actually transferred. (This is true on both 32-bit and 64-bit systems.)

所以神奇的数字是从那里来的。

为避免您的问题,请使用 write_all 而不是 write,这将确保所有字节都已写入。

注意:如果您 运行 Windows 下的程序,那么 运行 就好了。