Rust 实战练习 - 2. OS,IO,Platform(注册表,/etc)

目标:

  • 检测OS类型和基础信息
  • File 和 IO 模块
  • /etc或者注册表

OS related

rust 复制代码
use std::env;

fn main() {
    println!("OS module is not for check OS!\r\n");
    println!("Use ENV to detect OS info:");
    println!("OS: {}", env::consts::OS);
    println!("ARCH: {}", env::consts::ARCH);
    println!("FAMILY: {}", env::consts::FAMILY);
    println!("DLL_EXTENSION: {}", env::consts::DLL_EXTENSION);
    println!("EXE_EXTENSION: {}", env::consts::EXE_EXTENSION);

    if cfg!(windows) {
        println!("windows os!");
    }else if cfg!(unix) { 
        println!("unix os!")
    }else {
        println!("unknown os!")
    }

    println!("If need more info, need third part package: sysinfo");

}

io, file

rust 复制代码
use std::fs::File;
use std::io::{BufWriter, Read, Seek, SeekFrom, Write};

fn main() {
    {
        println!("Read Cargo.toml content!\r\n");
        let mut f = File::open("Cargo.toml").unwrap();
        let mut buf = [0u8; 1024];
        _ = f.seek(SeekFrom::Start(0));
        let n = f.read(&mut buf).unwrap();
        println!(
            "read {} byte, content: {}",
            n,
            String::from_utf8_lossy(&buf[..n])
        );
        _ = f.flush(); // 不用关闭,因为f超出作用域会自动Drop关闭
    }
    {
        // write
        println!("Create is write-only mode.\r\n");
        let f = File::create("fs.tmp").unwrap();
        let mut w = BufWriter::new(f);
        _ = w.write("abc hello 历史不会忘记你!".as_bytes());
        w.flush().unwrap();
    }
    {
        // Option
        println!("open is read-only mode, but option can change it.\r\n");
        let mut f = File::options().append(true).open("fs.tmp").unwrap();
        _ = f.write("xxxxxxxxxxxxx".as_bytes());
        _ = f.flush();
    }
    {
        // dev info
        let mut f = File::open("/proc/version").unwrap();
        let mut strbuf = String::new();
        _ = f.read_to_string(&mut strbuf);
        println!("{}", strbuf);
    }
}

etc 或 注册表

相关推荐
CC.GG3 分钟前
【C++】AVL树
java·开发语言·c++
CoderCodingNo17 分钟前
【GESP】C++四级真题 luogu-B4416 [GESP202509 四级] 最长连续段
开发语言·c++·算法
a程序小傲20 分钟前
京东Java面试被问:Fork/Join框架的使用场景
java·开发语言·后端·postgresql·面试·职场和发展
想用offer打牌23 分钟前
面试官问Redis主从延迟导致脏数据读怎么解决?
redis·后端·面试
⑩-24 分钟前
Java四种线程创建方式
java·开发语言
月光在发光25 分钟前
22_GDB调试记录(未完成)
java·开发语言
222you26 分钟前
SpringAOP的介绍和入门
java·开发语言·spring
程序员zgh28 分钟前
代码重构 —— 读后感
运维·c语言·开发语言·c++·重构
liulilittle35 分钟前
moodycamel::ConcurrentQueue 清空队列的方法论
开发语言·c++
shoubepatien37 分钟前
JAVA -- 09
java·开发语言