在Linux中,Rust使用标准库中的std::fs模块和std::io模块来处理文件I/O。以下是一些基本的文件I/O操作:
use std::fs::File;
use std::io::{self, Read, Write};
fn main() -> io::Result<()> {
let mut file = File::open("example.txt")?;
// ...
}
use std::fs::File;
use std::io::{self, Read};
fn main() -> io::Result<()> {
let mut file = File::open("example.txt")?;
let mut contents = String::new();
file.read_to_string(&mut contents)?;
println!("File contents: {}", contents);
Ok(())
}
use std::fs::File;
use std::io::{self, Write};
fn main() -> io::Result<()> {
let mut file = File::create("example.txt")?;
let contents = "Hello, world!";
file.write_all(contents.as_bytes())?;
Ok(())
}
use std::fs::File;
use std::io::{self, Write};
fn main() -> io::Result<()> {
let mut file = File::open("example.txt")?;
let contents = "\nNew line!";
file.write_all(contents.as_bytes())?;
Ok(())
}
use std::fs::File;
use std::io::{self, Write};
fn main() -> io::Result<()> {
let mut file = File::create("example.txt")?;
let contents = "Hello, world!";
file.write_all(contents.as_bytes())?;
drop(file); // 显式关闭文件
Ok(())
}
use std::fs::File;
use std::io::{self, BufRead, BufReader, BufWriter, Write};
fn main() -> io::Result<()> {
let file = File::open("example.txt")?;
let reader = BufReader::new(file);
let file = File::create("output.txt")?;
let mut writer = BufWriter::new(file);
for line in reader.lines() {
writeln!(writer, "{}", line?)?;
}
writer.flush()?; // 刷新缓冲区,将数据写入文件
Ok(())
}
这些示例展示了如何在Rust中使用标准库进行基本的文件I/O操作。你可以根据自己的需求选择合适的方法。