녹으로 파일 시스템을 제어하다
개발 중인 프로그램이나 유틸리티의 유형에 따라 파일 시스템을 처리해야 할 때가 있을 수 있습니다.
만약 어떤 데이터 저장소를 만들 때 Postgres나 MySQL 같은 데이터베이스를 사용하지 않았다면, 파일에 데이터를 저장할 수 있습니다.
만약 당신이 오디오나 동영상을 작성하기 위해 소프트웨어를 작성하고 있다면, 이 파일들을 작성하고 읽을 수 있어야 한다.
구축
create-react-app 이나 cargo new 같은 프로젝트를 돕는 유틸리티를 만들고 있다면, 파일 시스템을 사용해서 템플릿 디렉터리와 파일을 만들고 싶을 수도 있습니다.목표가 무엇이든지
std::fs 명칭 공간에서 자주 사용하는 방법을 이해하는 것이 도움이 될 것입니다. 프로젝트를 구축할 때, 프로젝트를 계속 찾을 것입니다.주요 기능 개요 
Docs: The docs for the fs crate are available here.
 
파일 읽기
 
Note: If you do not yet understand how generic function parameters work, you can read this chapter in the Rust Book.
For example, a path, P, is defined to be any type which implements a method which implements the trait AsRef<Path>.
 
기본부터 std::fs::read 의 함수 서명입니다.
fn read<P: AsRef<Path>>(path: P) -> io::Result<Vec<u8>>
주어진 경로의 파일을 읽고 바이트 벡터를 되돌려 주는 방법 fs 을 사용할 수 있습니다.사용법은 다음과 같습니다.
use std::fs;
use std::path::Path;
fn main() {
  let path = Path::new("screenshot.png");
  let data = fs::read(path).unwrap();
  // do something with `data`
}
read 방법은 실제로File::open와std::fs::read_to_end 호출이 편리한 포장기이다.이것은 매우 좋다. 왜냐하면 우리는 더 간단한 read 방법을 희생하지 않고 세립도의 저급 함수에 접근할 수 있기 때문이다.
pub fn read<P: AsRef<Path>>(path: P) -> io::Result<Vec<u8>> {
    fn inner(path: &Path) -> io::Result<Vec<u8>> {
        let mut file = File::open(path)?;
        let mut bytes = Vec::with_capacity(initial_buffer_size(&file));
        file.read_to_end(&mut bytes)?;
        Ok(bytes)
    }
    inner(path.as_ref())
}
서류를 쓰다
 
다음은 fs::write의 함수 서명입니다.
fn write<P: AsRef<Path>, C: AsRef<[u8]>>(path: P, contents: C) -> Result<()>
바이트 슬라이스로 사용할 데이터가 있다면 경로에 있는 파일에 쓸 수 있습니다.
write 방법은 부작용일 뿐이기 때문에 되돌아오는 것은 Result 형식일 뿐입니다. 문제가 발생하면 단원이나 오류로 해석됩니다.
use std::fs;
use std::path::Path;
fn main() {
  let path = Path::new("hello.txt");
  let contents = "hello there";
  fs::write(path, contents).unwrap();
}
read 방법과 마찬가지로 write는 File::create와 std::io::write_all의 편리한 포장기이다.다음은 실제 수행 상황입니다.
pub fn write<P: AsRef<Path>, C: AsRef<[u8]>>(path: P, contents: C)
  -> io::Result<()> {
    fn inner(path: &Path, contents: &[u8]) -> io::Result<()> {
        File::create(path)?.write_all(contents)
    }
    inner(path.as_ref(), contents.as_ref())
}
fs::read와fs::write에 대해 우리는 범주형 유형의 매개 변수가 작용하는 것을 볼 수 있다.P 매개 변수에 대해 우리는 그 중의 한 방법을 호출할 때 str, String, Path 또는 PathBuf 등의 유형을 사용할 수 있다.
표준 라이브러리는 특정한 유형의 매개 변수를 가진 inner 함수를 정의하는 모델을 사용합니다.그리고 as_reftrait에 필요한 함수AsRef를 강제로 변환한 후 가장 바깥쪽 인자로 호출합니다.
나의 목표는 일반적인 유형과 특징을 설명하는 것이 아니지만, 표준 라이브러리를 어떻게 사용하는지 탐색하는 것은 매우 식견이 있는 것이다.
예: 파일 복사
 
유닉스의 cp 명령과 같은 파일을 한 디렉터리에서 다른 디렉터리로 복사하려고 한다면.
우리는 이렇게 할 수 있다.
use std::fs;
use std::path::Path;
fn main() {
  let input = Path::new("hello.txt");
  let data = fs::read(input).unwrap();
  let output = Path::new("hello_copy.txt");
  fs::write(output, data).unwrap();
}
Rust의 fs 라이브러리는 우리에게 또 다른 편리한 방법을 제공했다fs::copy.
use std::fs;
use std::path::Path;
fn main() {
  let input = Path::new("hello.txt");
  let output = Path::new("hello_copy.txt");
  fs::copy(input, output).unwrap();
}
기타 유용한 방법
 
읽기와 쓰기는 파일 시스템의 더 뚜렷한 용도임에 틀림없지만, 일반적으로 완전한 응용 프로그램은 디렉터리 처리와 같은 다른 기능도 포함할 것이다.
읽기 도구:
Docs: The docs for the fs crate are available here.
Note: If you do not yet understand how generic function parameters work, you can read this chapter in the Rust Book.
For example, a path, P, is defined to be any type which implements a method which implements the trait AsRef<Path>.
fn read<P: AsRef<Path>>(path: P) -> io::Result<Vec<u8>>
use std::fs;
use std::path::Path;
fn main() {
  let path = Path::new("screenshot.png");
  let data = fs::read(path).unwrap();
  // do something with `data`
}
pub fn read<P: AsRef<Path>>(path: P) -> io::Result<Vec<u8>> {
    fn inner(path: &Path) -> io::Result<Vec<u8>> {
        let mut file = File::open(path)?;
        let mut bytes = Vec::with_capacity(initial_buffer_size(&file));
        file.read_to_end(&mut bytes)?;
        Ok(bytes)
    }
    inner(path.as_ref())
}
fn write<P: AsRef<Path>, C: AsRef<[u8]>>(path: P, contents: C) -> Result<()>
use std::fs;
use std::path::Path;
fn main() {
  let path = Path::new("hello.txt");
  let contents = "hello there";
  fs::write(path, contents).unwrap();
}
pub fn write<P: AsRef<Path>, C: AsRef<[u8]>>(path: P, contents: C)
  -> io::Result<()> {
    fn inner(path: &Path, contents: &[u8]) -> io::Result<()> {
        File::create(path)?.write_all(contents)
    }
    inner(path.as_ref(), contents.as_ref())
}
use std::fs;
use std::path::Path;
fn main() {
  let input = Path::new("hello.txt");
  let data = fs::read(input).unwrap();
  let output = Path::new("hello_copy.txt");
  fs::write(output, data).unwrap();
}
use std::fs;
use std::path::Path;
fn main() {
  let input = Path::new("hello.txt");
  let output = Path::new("hello_copy.txt");
  fs::copy(input, output).unwrap();
}
fs::read_to_string - String 바이트가 아닌 [u8] 바이트로 파일 내용을 반환fs::read_dir - 디렉토리작성 유틸리티:
fs::create_dir - 지정된 경로에 새 빈 디렉토리를 생성합니다.fs::create_dir_all - 경로가 부족하면 필요한 모든 디렉터리를 다시 만듭니다fs::rename - 유닉스mv 명령과 유사한 파일이나 디렉터리를 주어진 이름으로 이름 바꾸기유틸리티를 삭제하려면 다음과 같이 하십시오.
fs::remove_file - 지정된 파일 삭제fs::remove_dir - 지정된 빈 디렉토리 삭제fs::remove_dir_all - 디렉터리와 모든 내용을 삭제합니다(이 디렉터리 조심하세요)읽어주셔서 감사합니다.
나는 네가 이 문장을 좋아하거나 그것에 도움이 되기를 바란다.나는 현재 프로젝트를 하나 하고 있는데, 그 중의 몇 가지 방법을 사용하여 나 자신의 발전에 도움이 되는 것을 만들고 있다.
다음에 제가 Rust,ReasonML,GraphQL 또는 전체 소프트웨어 개발 분야에서 글을 발표할 때 제 걸음걸이를 따라오고 싶으면 언제든지 후속 정보를 주시거나 제 사이트ianwilson.io에 올려주세요.
Reference
이 문제에 관하여(녹으로 파일 시스템을 제어하다), 우리는 이곳에서 더 많은 자료를 발견하고 링크를 클릭하여 보았다 https://dev.to/iwilsonq/mastering-the-file-system-with-rust-135g텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
                                
                                
                                
                                
                                
                                우수한 개발자 콘텐츠 발견에 전념
                                (Collection and Share based on the CC Protocol.)