[Learn Rust programming with Xiaojia] 22. Commonly used APIs

Series Article Directory

[Learn Rust programming with Xiaojia] 1. Basics of Rust programming
[Learn Rust programming with Xiaojia] 2. Use of Rust package management tools
[Learn Rust programming with Xiaojia] 3. Basic programming concepts of Rust
[Learn Rust programming with Xiaojia] 】4. Understand the concept of ownership in Rust
【Learn Rust programming from Xiaojia】5. Use structures to associate structured data
【Learn Rust programming from Xiaojia】6. Enumeration and pattern matching
【Learn Rust programming from Xiaojia】7. Use packages (Packages), unit packages (Crates) and modules (Module) to manage projects
[Learn Rust programming with Xiaojia] 8. Common collections
[Learn Rust programming with Xiaojia] 9. Error handling (Error Handling)
[Follow Xiao Jia learns Rust programming] 11. Write automated tests
[Learn Rust programming with Xiao Jia] 12. Build a command line program
[Learn Rust programming with Xiao Jia] 13. Functional language features: iterators and closures
[ Learn Rust Programming from Xiaojia] 14. About Cargo and Crates.io
[Learn Rust Programming from Xiaojia] 15. Smart Pointer (Smart Point)
[Learn Rust Programming from Xiaojia] 16. Fearless Concurrency
[Learn Rust programming with Xiaojia] 17. Object-oriented language features
[Learn Rust programming with Xiaojia] 18. Pattern matching (Patterns and Matching)
[Learn Rust programming with Xiaojia] 19. Advanced features
[Learn Rust programming with Xiaojia] Learn Rust programming] Twenty, advanced extension
[Learn Rust programming with Xiaojia] 21. Network programming
[Learn Rust programming with Xiaojia] 22. Commonly used APIs

foreword

This chapter explains the Rust standard library std::fs, std::io, std::path, std::collections, std::env and other common APIs.

For the main teaching material, please refer to "The Rust Programming Language".
For the main teaching material, please refer to "Rust For Rustaceans". For the main teaching material, please refer to "
The Rustonomicon ".


One, the file system (FileSystem)

std::fs provides structures such as File, FileType, Metadata, OpenOptions, Permissions, ReadDir, DirEntry, DirBuilder, and FileTimes.

1.1. Directory operation

1.1.1. Create directory

We use the DirBuilder builder to recursively create a directory structure, which uses a chain call method to use

#![allow(unused)]
use std::fs::{
    
    self, DirBuilder};
fn main() {
    
    
    let path = "/tmp/foo/bar/baz";
    DirBuilder::new()
        .recursive(true)
        .create(path).unwrap();
    assert!(fs::metadata(path).unwrap().is_dir());
}

You can also use the create_dir and create_dir_all methods to create directories

pub fn create_dir<P: AsRef<Path>>(path: P) -> Result<()>
pub fn create_dir_all<P: AsRef<Path>>(path: P) -> Result<()>

1.1.2, read directory

We can use the fs::read_dir method to read the directory, and what is returned is that Result<DirEntry>DirEntry provides methods for obtaining file metadata information (Metadata) and file paths.

  • We can use metadata information to obtain file permission information, determine file type, obtain file size (len), file modification time, access time, and creation time
  • The file_type method can obtain the file type, and the filetype can be used to determine whether the file is a directory, whether it is a file, or whether it is a link file;
  • The file_name method can get the file name;
#![allow(unused)]
use std::fs;
use std::io;

fn main() -> io::Result<()>{
    
    
    for entry in fs::read_dir(".")?{
    
    
        if let Ok(entry) = entry {
    
    

            if let Ok(file_type) = entry.file_type() {
    
    
                println!("{:?}: {:?}", entry.path(), file_type);
            }else {
    
    
                println!("Couldn't get file type for {:?}", entry.path());
            }

            if let Ok(metadata)  = entry.metadata(){
    
    
                println!("{:?}: {:?}", entry.path(), metadata.permissions());
            }else {
    
    
                println!("Couldn't get metadata for {:?}", entry.path());
            }
        }
    }
 
    Ok(())
}

1.1.3. Delete directory

pub fn remove_dir<P: AsRef<Path>>(path: P) -> Result<()>
pub fn remove_dir_all<P: AsRef<Path>>(path: P) -> Result<()>

1.2. File operation

1.2.1, file copy

Use the fs::copy method to implement file copying, you can refer to the io::copy method

#![allow(unused)]
use std::fs;
use std::io;

fn main() -> io::Result<()>{
    
    
  
    fs::copy("foo.txt", "bar.txt")?;  // Copy foo.txt to bar.txt
 
    Ok(())
}

1.2.2. File reading

You can use the fs::read method to read the file content, and you can refer to the File::open and read_to_end and read_to_string methods for file reading

pub fn read<P: AsRef<Path>>(path: P) -> Result<Vec<u8>>

In addition, we can also use BufReader to read files line by line;

 let reader = BufReader::new(file);
    for line in reader.lines() {
    
    
        println!("{}", line?);
    }

A file with a buffer can also be read using the file.read method;

1.2.3. Delete files

pub fn remove_file<P: AsRef<Path>>(path: P) -> Result<()>

1.2.4. File renaming

pub fn rename<P: AsRef<Path>, Q: AsRef<Path>>(from: P, to: Q) -> Result<()>

1.2.5. Write to file

pub fn write<P: AsRef<Path>, C: AsRef<[u8]>>(path: P, contents: C) -> Result<()>

You can also use BufWriter for file writing

1.2.6. Set file permissions

pub fn set_permissions<P: AsRef<Path>>(path: P, perm: Permissions) -> Result<()>

The file structure also provides methods for setting permissions

pub fn set_permissions(&self, perm: Permissions) -> Result<()>

1.2.7. Create file

Use the File::create method to create a file, which is a write-only file.

use std::fs::File;
use std::io::Write;

fn main() -> std::io::Result<()> {
    
    
    let mut f = File::create("foo.txt")?;
    f.write_all(&1234_u32.to_be_bytes())?;
    Ok(())
}

We can also use chain calls to create and open files

fs::File::options().read(true).write(true).create_new(true).open("test.txt");

OpenOptions::new().read(true).write(true)create(true).open("foo.txt");

Two, standard input and output

2.1, standard input

Use io::stdin to get a Stdin object, which represents standard input.

let mut input = String::new();
match io::stdin().read_line(&mut input) {
    
    
    Ok(n) => {
    
    
        println!("{n} bytes read");
        println!("{input}");
    }
    Err(error) => println!("error: {error}"),
}

2.1, standard output

Use os::stdout to get the Stdoout object. Strings can be output to standard output. We generally don't use it this way;

3. Collection operations

std::collections provides BTreeMap, BTreeSet, BinaryHeap, HashMap, HashSet, LinkedList, VecDeque and other data structures

Summarize

That's all for today

Guess you like

Origin blog.csdn.net/fj_Author/article/details/132594511