FS Structs
File system types ใน Rust สำหรับ working with files, directories, และ metadata
1. File
Section titled “1. File”File represents an open file handle
Working with Files
Section titled “Working with Files”use std::fs::File;use std::io::{Read, Write, Seek, SeekFrom};
fn main() -> std::io::Result<()> { // Create new file (or truncate existing) let mut file = File::create("/tmp/test_rust.txt")?; file.write_all(b"Hello, World!")?;
// Open for reading let mut file = File::open("/tmp/test_rust.txt")?; let mut contents = String::new(); file.read_to_string(&mut contents)?; println!("Contents: {}", contents);
// Open with custom options let file = std::fs::OpenOptions::new() .read(true) .write(true) .create(true) .open("/tmp/test_rust.txt")?;
// Get file metadata let metadata = file.metadata()?; println!("Size: {} bytes", metadata.len()); println!("Modified: {:?}", metadata.modified()?); println!("Is file: {}", metadata.is_file());
// Sync to disk file.sync_all()?; // Sync data and metadata file.sync_data()?; // Sync data only (faster)
// Clone file handle let _clone = file.try_clone()?;
Ok(())}เข้าสู่ระบบเพื่อดูเนื้อหาเต็ม
ยืนยันตัวตนด้วยบัญชี Google เพื่อปลดล็อกบทความทั้งหมด
Login with Google