RUST安装和配置过程及第一章节代码实现

RUST安装和配置过程及第一章节代码实现

在Linux系统下,安装RUST

sudo sh -c "curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh"

可能会有报错如下

  • 检查 /tmp 权限
    确保 /tmp 目录具有正确的权限,允许所有用户写入。可以使用以下命令检查 /tmp 目录的权限:
    ls -ld /tmp
  • 正确的权限应该是 drwxrwxrwt。如果不是,你可以使用以下命令来设置正确的权限:
    sudo chmod 1777 /tmp

清理 /tmp 目录

首先,清理 /tmp 目录,以确保有足够的空间进行文件写入。可以安全地删除 /tmp 目录中的大多数文件,因为这些文件通常是临时的,系统重启后会重新创建。使用以下命令来清理:
sudo rm -rf /tmp/*

检查磁盘空间

df -h

如果仍然报错,可以尝试手动下载rustup-init

在浏览器中或使用 wget 命令下载文件到你的主目录或其他有足够空间的目录:
wget https://static.rust-lang.org/rustup/dist/x86_64-unknown-linux-gnu/rustup-init

赋予下载的文件执行权限,并运行它:

chmod +x rustup-init
./rustup-init

继续标准安装(默认 - 只需按回车键):

  • 这将安装默认的工具链(stable)、默认配置文件,并将 Rust 相关的命令添加到你的 PATH 环境变量中。

安装完成后,需要重新启动终端或运行以下命令来激活 Rust 环境变量的更改,

source ~/.profile
source ~/.bashrc
  • 然后通过运行 rustc --version 和 cargo --version 来验证 Rust 和 Cargo 是否正确安装

开始使用 Rust

创建一个新的项目

使用 cargo 创建一个名为 hello_world 的新项目:

cargo new hello_world
cd hello_world

查看和修改代码

打开 src/main.rs 文件,它应该包含以下 Rust 代码:

fn main() {
    println!("Hello, world!");
}

编译并运行项目

在项目目录中,使用 cargo run 命令来编译并运行你的程序:
cargo run

more1rust实现

  • c代码
/* more01.c  - version 0.1 of more
 *	read and print 24 lines then pause for a few special commands
 */

#include	<stdio.h>

#define	PAGELEN	24
#define	LINELEN	512

void do_more(FILE *);
int  see_more();

int main( int ac , char *av[] )
{
	FILE	*fp;

	if ( ac == 1 )
		do_more( stdin );
	else
		while ( --ac )
			if ( (fp = fopen( *++av , "r" )) != NULL )
			{
				do_more( fp ) ; 
				fclose( fp );
			}
			else
				exit(1);
	return 0;
}

void do_more( FILE *fp )
/*
 *  read PAGELEN lines, then call see_more() for further instructions
 */
{
	char	line[LINELEN];
	int	num_of_lines = 0;
	int	see_more(), reply;

	while ( fgets( line, LINELEN, fp ) ){		/* more input	*/
		if ( num_of_lines == PAGELEN ) {	/* full screen?	*/
			reply = see_more();		/* y: ask user  */
			if ( reply == 0 )		/*    n: done   */
				break;
			num_of_lines -= reply;		/* reset count	*/
		}
		if ( fputs( line, stdout )  == EOF )	/* show line	*/
			exit(1);			/* or die	*/
		num_of_lines++;				/* count it	*/
	}
}

int see_more()
/*
 *	print message, wait for response, return # of lines to advance
 *	q means no, space means yes, CR means one line
 */
{
	int	c;

	printf("\033[7m more? \033[m");		/* reverse on a vt100	*/
	while( (c=getchar()) != EOF )			/* get response	*/
	{
		if ( c == 'q' )			/* q -> N		*/
			return 0;
		if ( c == ' ' )			/* ' ' => next page	*/
			return PAGELEN;		/* how many to show	*/
		if ( c == '\n' )		/* Enter key => 1 line	*/
			return 1;		
	}
	return 0;
}
  • rust实现
use std::fs::File;
use std::io::{self, BufRead, BufReader, Write};

const PAGELEN: usize = 24;
const LINELEN: usize = 512;

fn main() {
    let args: Vec<String> = std::env::args().collect();
    if args.len() == 1 {
        do_more(io::stdin().lock());
    } else {
        for filename in &args[1..] {
            let file = File::open(filename).expect("无法打开文件");
            let reader = BufReader::new(file);
            do_more(reader);
        }
    }
}

fn do_more<R: BufRead>(mut reader: R) {
    let mut line = String::new();
    let mut line_count = 0;

    while reader.read_line(&mut line).unwrap() > 0 {
        if line.len() > LINELEN {
            line.truncate(LINELEN);
        }
        print!("{}", line);

        line_count += 1;
        if line_count == PAGELEN {
            let response = see_more();
            if response == 0 {
                break;
            }
            line_count -= response;
        }

        line.clear();
    }
}

fn see_more() -> usize {
    print!("\x1B[7m 还要继续查看吗? \x1B[m");
    io::stdout().flush().unwrap();
    let mut input = String::new();
    io::stdin().read_line(&mut input).unwrap();
    match input.trim() {
        "q" => 0,
        " " => PAGELEN,
        "\n" => 1,
        _ => 0,
    }
}

more2rust实现

c语言代码

/*  more02.c  - version 0.2 of more
 *	read and print 24 lines then pause for a few special commands
 *      feature of version 0.2: reads from /dev/tty for commands
 */
#include	<stdio.h>

#define	PAGELEN	24
#define	LINELEN	512

void do_more(FILE *);
int see_more(FILE *);

int main( int ac , char *av[] )
{
	FILE	*fp;

	if ( ac == 1 )
		do_more( stdin );
	else
		while ( --ac )
			if ( (fp = fopen( *++av , "r" )) != NULL )
			{
				do_more( fp ) ; 
				fclose( fp );
			}
			else
				exit(1);
	return 0;
}

void do_more( FILE *fp )
/*
 *  read PAGELEN lines, then call see_more() for further instructions
 */
{
	char	line[LINELEN];
	int	num_of_lines = 0;
	int	see_more(FILE *), reply;
	FILE	*fp_tty;

	fp_tty = fopen( "/dev/tty", "r" );	   /* NEW: cmd stream   */
	if ( fp_tty == NULL )			   /* if open fails     */
		exit(1);                           /* no use in running */

	while ( fgets( line, LINELEN, fp ) ){		/* more input	*/
		if ( num_of_lines == PAGELEN ) {	/* full screen?	*/
			reply = see_more(fp_tty);  /* NEW: pass FILE *  */
			if ( reply == 0 )		/*    n: done   */
				break;
			num_of_lines -= reply;		/* reset count	*/
		}
		if ( fputs( line, stdout )  == EOF )	/* show line	*/
			exit(1);			/* or die	*/
		num_of_lines++;				/* count it	*/
	}
}

int see_more(FILE *cmd)				   /* NEW: accepts arg  */
/*
 *	print message, wait for response, return # of lines to advance
 *	q means no, space means yes, CR means one line
 */
{
	int	c;

	printf("\033[7m more? \033[m");		/* reverse on a vt100	*/
	while( (c=getc(cmd)) != EOF )		/* NEW: reads from tty  */
	{
		if ( c == 'q' )			/* q -> N		*/
			return 0;
		if ( c == ' ' )			/* ' ' => next page	*/
			return PAGELEN;		/* how many to show	*/
		if ( c == '\n' )		/* Enter key => 1 line	*/
			return 1;		
	}
	return 0;
}
  • rust代码
use std::fs::File;
use std::io::{self, BufRead, BufReader, Write};

const PAGELEN: usize = 24;
const LINELEN: usize = 512;

fn main() {
    let args: Vec<String> = std::env::args().collect();
    if args.len() == 1 {
        do_more(io::stdin().lock());
    } else {
        for filename in &args[1..] {
            if let Ok(file) = File::open(filename) {
                do_more(BufReader::new(file));
            } else {
                eprintln!("无法打开文件 {}", filename);
                std::process::exit(1);
            }
        }
    }
}

fn do_more<R: BufRead>(mut reader: R) {
    let mut line = String::new();
    let mut line_count = 0;
    let mut input = io::BufReader::new(File::open("/dev/tty").expect("无法打开 /dev/tty"));

    while reader.read_line(&mut line).unwrap_or(0) > 0 {
        if line.len() > LINELEN {
            line.truncate(LINELEN);
        }
        print!("{}", line);
        io::stdout().flush().unwrap();

        line_count += 1;
        if line_count == PAGELEN {
            let response = see_more(&mut input);
            if response == 0 {
                break;
            }
            line_count -= response;
        }

        line.clear();
    }
}

fn see_more(input: &mut io::BufReader<File>) -> usize {
    print!("\x1B[7m more? \x1B[m");
    io::stdout().flush().unwrap();
    let mut cmds = String::new();
    input.read_line(&mut cmds).unwrap();

    match cmds.as_str().trim() {
        "q" => 0,
        " " => PAGELEN,
        "\n" => 1,
        _ => 0,
    }
}

more01和more02的区别

Version 0.1 (more01.c)

这是更简单的实现版本。它的主要特点包括:

  • 用户输入:用户输入直接从标准输入(stdin)读取。这意味着如果程序的输出被重定向到文件或其他设备,用户输入仍然来自终端,可能会导致交互混乱或不可用。
  • 交互逻辑:在显示完 24 行后,程序使用 see_more() 函数来获取用户输入,并决定是否继续显示更多内容、显示下一行或退出。
  • 输入处理:处理的输入包括空格(显示下一页)、回车(显示下一行)和 'q'(退出程序)。

Version 0.2 (more02.c)

这个版本在功能上对 version 0.1 进行了改进,尤其是在输入处理方面:

  • 输入源:此版本引入了从 /dev/tty 读取用户命令的新功能。/dev/tty 代表当前终端,即使程序的标准输入和输出被重定向,从 /dev/tty 读取输入可以保证用户命令的正常交互。这是一个重要的改进,因为它允许程序在多种上下文中更可靠地工作,特别是在输出被重定向的情况下。
  • 错误处理:在打开 /dev/tty 失败时,程序会直接退出,这意味着如果没有有效的方式来读取用户输入,程序不会尝试运行。
posted @ 2024-06-08 17:28  LLLZTTT  阅读(28)  评论(0编辑  收藏  举报
$