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");
}