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

相关推荐
武子康12 分钟前
Java-72 深入浅出 RPC Dubbo 上手 生产者模块详解
java·spring boot·分布式·后端·rpc·dubbo·nio
椰椰椰耶2 小时前
【Spring】拦截器详解
java·后端·spring
brzhang3 小时前
我操,终于有人把 AI 大佬们 PUA 程序员的套路给讲明白了!
前端·后端·架构
倔强青铜33 小时前
苦练Python第18天:Python异常处理锦囊
开发语言·python
u_topian4 小时前
【个人笔记】Qt使用的一些易错问题
开发语言·笔记·qt
珊瑚里的鱼4 小时前
LeetCode 692题解 | 前K个高频单词
开发语言·c++·算法·leetcode·职场和发展·学习方法
AI+程序员在路上4 小时前
QTextCodec的功能及其在Qt5及Qt6中的演变
开发语言·c++·qt
xingshanchang4 小时前
Matlab的命令行窗口内容的记录-利用diary记录日志/保存命令窗口输出
开发语言·matlab
Risehuxyc4 小时前
C++卸载了会影响电脑正常使用吗?解析C++运行库的作用与卸载后果
开发语言·c++
AI视觉网奇4 小时前
git 访问 github
运维·开发语言·docker