c语言printf实现同一位置打印输出的实例

 更新时间:2020年4月25日 17:29  点击:2228

控制台同一位置打印输出,例如:进度1%->100%在同一位置显示。刚学习c语言的时候一直想做起来,可惜查询好多资料不行。时隔6年多,空闲之余又想起这个问题,便决定一试,虽然c语言已经几乎忘光了,呵呵。最终还是搞定了,这次运气不错,哈哈! ^_^

#include <stdio.h>
#include <pthread.h>
//#include <sys/time.h>

//linux for sleep(seconds) and usleep(Microsecond)
//#include <unistd.h>

//windows for Sleep(millisecond)
//#include <windows.h> 


//创建线程函数返回类型
pthread_t thread[1]; 

/**
* 线程函数
**/
void *printThread(){
 printf("%s\n","线程开始处理任务");

 printf("已经处理了:");
 for(int i = 1; i <= 100; i++) {
 if(i==1){
 //数字占3格,%占一格
 printf("%3d%%",i);
 }else{
 //退4格
 printf("\b\b\b\b%3d%%",i); 
 }
 //即时标准输出(不带\n,不刷新不行)
 fflush(stdout);
 //延时1秒
 sleep(1);
 }
}


int main(){

 printf("我是主函数哦,我正在创建线程,呵呵\n");
 /*创建线程*/
 if(pthread_create(&thread[0], NULL, printThread, NULL)!=0){
 printf("线程创建失败\n");
 }
 printf("线程创建成功\n");

 printf("我是主函数哦,我正在等待线程完成任务阿,呵呵\n");
 /*等待线程结束*/
 pthread_join(thread[0],NULL);
 printf("\n线程已经结束\n");

 return 1;
}

代码是在mac os下测试成功的。window系统需要在编译器中引入pthread库,参考实例 Windows下使用Dev-C++开发基于pthread.h的多线程程序

以上这篇c语言printf实现同一位置打印输出的实例就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持猪先飞。

[!--infotagslink--]

相关文章