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

相关推荐
菜鸟小芯6 分钟前
Qt Creator 集成开发环境下载安装
开发语言·qt
阿猿收手吧!19 分钟前
【C++】引用类型全解析:左值、右值与万能引用
开发语言·c++
「QT(C++)开发工程师」23 分钟前
C++ 策略模式
开发语言·c++·策略模式
iFeng的小屋34 分钟前
【2026最新当当网爬虫分享】用Python爬取千本日本相关图书,自动分析价格分布!
开发语言·爬虫·python
yugi98783835 分钟前
基于MATLAB的一键式EMD、EEMD、CEEMD和SSA信号去噪实现
开发语言·matlab·信号去噪
热爱编程的小刘1 小时前
Lesson05&6 --- C&C++内存管理&模板初阶
开发语言·c++
Charlie_lll2 小时前
力扣解题-[3379]转换数组
数据结构·后端·算法·leetcode
qq_12498707532 小时前
基于Java Web的城市花园小区维修管理系统的设计与实现(源码+论文+部署+安装)
java·开发语言·前端·spring boot·spring·毕业设计·计算机毕业设计
VX:Fegn08952 小时前
计算机毕业设计|基于springboot + vue云租车平台系统(源码+数据库+文档)
数据库·vue.js·spring boot·后端·课程设计
froginwe112 小时前
Python 条件语句
开发语言