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 或 注册表

相关推荐
IT_陈寒25 分钟前
JavaScript项目实战经验分享
前端·人工智能·后端
用户47949283569151 小时前
6w star,GitHub 趋势第一的 Ponytail,这个agent插件到底在火什么
前端·后端
神奇小汤圆2 小时前
2026一线大厂Java八股文精选(附答案,高质量整理)
后端
Warson_L3 小时前
LangGraph入门学习资料
后端
神奇小汤圆3 小时前
Spring Boot → Solon 注解迁移实战指南:一张对照表说清楚
后端
kfaino3 小时前
码农的AI翻身(四)你好,我叫 Attention
人工智能·后端
lwx572803 小时前
探秘InnoDB:搞懂它的内存、线程、磁盘与日志刷盘策略
java·后端
云技纵横5 小时前
Spring Boot Actuator 被打穿:线上开了这些端点,等于裸奔
后端
Flynt5 小时前
从Spring Boot 4.0升到4.1,我在Maven和gRPC上栽了跟头
java·spring boot·后端
星栈6 小时前
我用 Rust + Dioxus 做了个全栈跨平台笔记应用:再把新建、编辑和交付补上
前端·rust·前端框架