use serde::{Serialize, Deserialize}; use std::fs::File; use std::io::prelude::*; fn main() -> std::io::Result<()>{ let mut file = File::open("foo.txt")?; let mut contents = String::new(); file.read_to_string(&mut contents)?; println!("{}", contents); assert_eq!(contents, "hello, world!"); Ok(()) }
$ cargo run
Finished `dev` profile [unoptimized + debuginfo] target(s) in 0.49s
Running `target/debug/sample`
bytes bytes bytes 8bytes
asdfghjkl
1234567890
thread ‘main’ panicked at src/main.rs:11:5:
assertion `left == right` failed
left: “bytes bytes bytes 8bytes\nasdfghjkl\n1234567890”
right: “hello, world!”
note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace
これも同じ
fn main() -> std::io::Result<()>{ let file = File::open("foo.txt")?; let mut buf_reader = BufReader::new(file); let mut contents = String::new(); buf_reader.read_to_string(&mut contents)?; println!("{}", contents); assert_eq!(contents, "hello, world!"); Ok(()) }
### 1行ずつ読み取る
use std::fs::File; use std::io::{BufReader, BufRead, Error}; fn main() -> Result<(), Error>{ let path = "foo.txt"; let input = File::open(path)?; let buffered = BufReader::new(input); for line in buffered.lines() { println!("{}", line?); } Ok(()) }
### ファイルの書き込み
fn main() -> std::io::Result<()>{ let mut buffer = File::create("hoge.txt")?; buffer.write_all(b"some bytes\n hogehoge")?; Ok(()) }
### 最終行に書き込み
use std::fs::OpenOptions; use std::io::Write; fn main() -> std::io::Result<()>{ let mut fileRef = OpenOptions::new() .append(true) .open("hoge.txt") .expect("Unable to open file"); fileRef.write_all(b"last line\n").expect("write failed"); Ok(()) }
改行コードを入れないと、同じ列になってしまう。
さて、Structでやりたい。