← λͺ©λ‘μœΌλ‘œ
Rust File I/O

동기식 파일 처리

use std::fs::File;
use std::io::{self, Read, Write};

fn main() -> io::Result<()> {
    // 파일 읽기
    let mut file = File::open("input.txt")?;
    let mut contents = String::new();
    file.read_to_string(&mut contents)?;

    // 파일 μ“°κΈ°
    let mut file = File::create("output.txt")?;
    file.write_all(contents.as_bytes())?;
    Ok(())
}

큰 νŒŒμΌμ„ λ‹€λ£° λ•Œμ—λŠ” BufReaderλ₯Ό μ‚¬μš©ν•˜λ©΄ λ©”λͺ¨λ¦¬λ₯Ό 효율적으둜 μ‚¬μš©ν•  수 μžˆμŠ΅λ‹ˆλ‹€.

use std::fs::File;
use std::io::{self, BufReader};

fn main() -> io::Result<()> {
    let file = File::open("large_file.txt")?;
    let reader = BufReader::new(file);

    for line in reader.lines() {
        println!("{}", line?);
    }
    Ok(())
}

비동기식 파일 처리

Tokioλ₯Ό μ‚¬μš©ν•˜λ©΄ λΉ„λ™κΈ°λ‘œ νŒŒμΌμ„ μ²˜λ¦¬ν•  수 μžˆμŠ΅λ‹ˆλ‹€. I/O μž‘μ—… 쀑 λ‹€λ₯Έ μž‘μ—…μ„ μˆ˜ν–‰ν•  수 μžˆμ–΄μ„œ μ›Ή μ„œλ²„λ‚˜ λ™μ‹œμ— μ—¬λŸ¬ νŒŒμΌμ„ μ²˜λ¦¬ν•΄μ•Ό ν•˜λŠ” κ²½μš°μ— μœ μš©ν•©λ‹ˆλ‹€.

use tokio::fs::File;
use tokio::io::{self, AsyncReadExt, AsyncWriteExt};

async fn handle_file() -> io::Result<()> {
    let mut file = File::open("input.txt").await?;
    let mut contents = String::new();
    file.read_to_string(&mut contents).await?;

    let mut file = File::create("output.txt").await?;
    file.write_all(contents.as_bytes()).await?;
    Ok(())
}

μ—¬λŸ¬ νŒŒμΌμ„ λ™μ‹œμ— μ²˜λ¦¬ν•  μˆ˜λ„ μžˆμŠ΅λ‹ˆλ‹€.

use tokio::fs;
use futures::future::join_all;

async fn process_files(files: Vec<String>) -> io::Result<()> {
    let handles: Vec<_> = files.into_iter()
        .map(|file| tokio::spawn(async move {
            let contents = fs::read_to_string(file).await?;
            // 파일 처리 둜직
            Ok::<(), io::Error>(())
        }))
        .collect();

    join_all(handles).await?;
    Ok(())
}

동기식 vs 비동기식

동기식은 μž‘μ—…μ΄ μ™„λ£Œλ  λ•ŒκΉŒμ§€ μŠ€λ ˆλ“œκ°€ λΈ”λ‘œν‚Ήλ˜μ§€λ§Œ κ΅¬ν˜„μ΄ λ‹¨μˆœν•©λ‹ˆλ‹€.
비동기식은 I/O λŒ€κΈ° 쀑 λ‹€λ₯Έ μž‘μ—…μ„ μˆ˜ν–‰ν•  수 μžˆμ§€λ§Œ tokio 같은 λŸ°νƒ€μž„μ΄ ν•„μš”ν•©λ‹ˆλ‹€.

CLI λ„κ΅¬λ‚˜ μ„€μ • 파일 λ‘œλ”©μ²˜λŸΌ λ‹¨μˆœν•œ κ²½μš°μ—λŠ” 동기식이 μ ν•©ν•˜κ³ , μ›Ή μ„œλ²„λ‚˜ λŒ€λŸ‰ 파일 μ²˜λ¦¬μ—λŠ” 비동기식이 μ ν•©ν•©λ‹ˆλ‹€.

μ„±λŠ₯ μ΅œμ ν™”

버퍼 크기λ₯Ό μ‘°μ •ν•˜κ±°λ‚˜ λ©”λͺ¨λ¦¬ 맀핑을 μ‚¬μš©ν•  수 μžˆμŠ΅λ‹ˆλ‹€.

use std::io::BufReader;

let file = File::open("large_file.txt")?;
let reader = BufReader::with_capacity(64 * 1024, file); // 64KB 버퍼
use memmap2::MmapOptions;

let file = File::open("large_file.txt")?;
let mmap = unsafe { MmapOptions::new().map(&file)? };