如何将控制台输出固定到位 [英] How to make console output fixed in place
本文介绍了如何将控制台输出固定到位的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我的LAME(v3.99.5)通过在控制台中上移x行并覆盖前几行来在控制台中输出进度.很酷.
My LAME (v3.99.5) outputs progress in console by moving up x lines in the console and overwriting the previous lines. It's pretty cool.
我已经阅读了不同的帖子仅使用"\ r"
而不是"\ n"
即可实现单行的这种行为-尽管该帖子是针对Ruby的,但似乎至少在我的系统上与 C 相同:
I've read in a different post that such behavior for a single line can be achieved with a mere "\r"
instead of "\n"
- although the post was for Ruby, it seems to be the same for C on my system at least:
#include <stdio.h>
#include <time.h>
int main() {
time_t t;
time_t t2;
time(&t);
t2 = t;
printf("%u\r", (unsigned int)t);
fflush(stdout);
while (1) {
if (t2 - t > 0) {
time(&t);
printf("%u\r", (unsigned int)t);
fflush(stdout);
}
time(&t2);
}
return 0;
}
该帖子进一步建议,可以使用 curses库来制作相同的行为多行.
The post further suggests a curses library can be used to make the same behavior multi-line.
C 中的此类代码的样板示例是什么?
What would be a boilerplate example of such code in C?
推荐答案
根据 Windows:
void SetCursorPos(int XPos, int YPos)
{
COORD Coord;
Coord.X = XPos;
Coord.Y = YPos;
SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE), Coord);
}
Linux:
void SetCursorPos(int XPos, int YPos)
{
printf("\033[%d;%dH", YPos+1, XPos+1);
}
这篇关于如何将控制台输出固定到位的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文