linux进度条小程序实现

linux进度条小程序实现

C语言中的\n和\r字符

C语言中字符分为两种:

        1.可显字符
        2.控制字符
其中可显字符就是字符a这类的字符,控制字符就是\n这种控制字符。

对于我们制作进度条,我们只需要关注两个控制字符:

        1.\r – 进行回车操作
        2.\n – 进行换行加回车操作
说明: \n本身是换行字符,但是C语言本身将其解析成了换行加回车。

为了更好地体会字符\r和\n的作用,我们需要做一些测试,为了方便进行编译,创建makefile文件,文件内容如下:

mytest:test.c
	gcc -o mytest test.c
.PHONY:clean
clean:
	rm -f mytest

mian.cc

#include <stdio.h>
#include <unistd.h>
int main()
{
	printf("hello world");
    sleep(3);
    fflush(stdout);
	return 0;
}

mytroc.cc

#include "myproc.h"
#include <string.h>
#include <unistd.h>

#define STYLE '='
#define ARROW '>'
#define SIZE 101

void process()
{
  char buf[SIZE];
  memset(buf, 0 , SIZE);
  int i = 0;
  while(i <= 100)
  {
    printf("[%-100s]\r", buf);
    fflush(stdout);
    buf[i++] = STYLE;
    if(i != 100 )buf[i] = ARROW;
    usleep(100000);
  }
  printf("\n");
}

test.cc

#include "myproc.h"
#include <string.h>
#include <unistd.h>

#define STYLE '='
#define ARROW '>'
#define SIZE 101

void process()
{
  const char* cursor = "|/-\\";
  char buf[SIZE];
  memset(buf, 0 , SIZE);
  int i = 0;
  while(i <= 100)
  {
    printf("[%-100s][%d%%][%c]\r", buf, i, cursor[i%4]);
    fflush(stdout);
    buf[i++] = STYLE;
    if(i != 100 )buf[i] = ARROW;
    usleep(100000);
  }
  printf("\n");
}

  • 4
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值