实现进度条

发布于:2025-08-20 ⋅ 阅读:(11) ⋅ 点赞:(0)

在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

进度条

1 补充 - 回⻋与换⾏

• 回⻋概念
• 换⾏概念
• ⽼式打字机的例⼦
• \r&&\n

2 ⾏缓冲区

什么现象?
#include <stdio.h>
int main()
{
printf(“hello bite!\n”);
sleep(3);
return 0;
}

什么现象??
#include <stdio.h>
int main()
{
printf(“hello bite!”);
sleep(3);
return 0;
}

什么现象???

int main()
{
printf("hello bite!");
fflush(stdout);
sleep(3);
return 0;
}

3 练⼿ - 倒计时程序

#include <unistd.h>

int main()
{
int i = 10;
while(i >= 0)
{
printf("%-2d\r", i); // \n
fflush(stdout);
i--;
sleep(1);
}
printf("\n");
return 0;
}

4 进度条代码

#include "process.h"
#include <string.h>
#include <unistd.h>
#define NUM 101
#define STYLE '='
// vesion1
void process_v1()
{
char buffer[NUM];
memset(buffer, 0, sizeof(buffer));
const char *lable="|/-\\";
int len = strlen(lable);
int cnt = 0;
while(cnt <= 100)
{
printf("[%-100s][%d%%][%c]\r", buffer, cnt, lable[cnt%len]);
fflush(stdout);
buffer[cnt]= STYLE;
cnt++;
usleep(50000);
}
printf("\n");

}
// verison2
void FlushProcess(double total, double current)
{
char buffer[NUM];
memset(buffer, 0, sizeof(buffer));
const char *lable="|/-\\";
int len = strlen(lable);
static int cnt = 0;
// 不需要⾃⼰循环,填充#
int num = (int)(current*100/total); // 11.0 / 1000
int i = 0;
for(; i < num; i++)
{
buffer[i] = STYLE;
}
double rate = current/total;
cnt %= len;
printf("[%-100s][%.1f%%][%c]\r", buffer, rate*100, lable[cnt]);
cnt++;
fflush(stdout);
}

process.h
#pragma once
#include <stdio.h>
void process_v1();
void FlushProcess(double total, double current);

main.c
$ cat main.c
#include "process.h"
#include <stdio.h>
#include <unistd.h>

double total = 1024.0;
double speed = 1.0;
void DownLoad()
{
double current = 0;
while(current <= total)
{
FlushProcess(total, current);
// 下载代码
usleep(3000); // 充当下载数据
current += speed;
}
printf("\ndownload %.2lfMB Done\n", current);
}
int main()
{
DownLoad();
DownLoad();
DownLoad();
DownLoad();
DownLoad();
DownLoad();
DownLoad();
DownLoad();
return 0;
}
SRC=$(wildcard *.c)
OBJ=$(SRC:.c=.o)
BIN=processbar
$(BIN):$(OBJ)
gcc -o $@ $^
%.o:%.c
gcc -c $<
.PHONY:
clean:
rm -f $(OBJ) $(BIN)

网站公告

今日签到

点亮在社区的每一天
去签到