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

控制台同一位置打印输出,例如:进度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
","线程开始处理任务");

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


int main(){

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

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

  return 1;
}

代码是在mac os下测试成功的。window系统需要在编译器中引入pthread库,可参考:https://yq.aliyun.com/articles/35576

简版

#include <stdio.h>

int main(){
    
    printf("已经处理了:");
    for(int i = 1; i <= 100; i++) {
        if(i==1){
            //数字占3格,%占一格
            printf("%3d%%",i);
        }else{
            //退4格
            printf("%3d%%",i);
        }
        //即时标准输出(不带
,不刷新不行)
        fflush(stdout);
        //延时10000微妙 = 10豪秒 = 0.01 秒
        //usleep(10000);
        //延时模拟
        int times = 10000000;
        while(times-->0){
            
        }
        
    }
    
    return 1;
}
原文地址:https://www.cnblogs.com/hdwang/p/7603259.html