Moving the cursor to the beginning of the current line
Asked Answered
P

4

10

I want to print current time (by using printf) in same place, but i want to do it in infinite loop eg:

while(1) {printf("Date and Time are %s", asctime(localtime(&current))); } 

So before I use printf I should move cursor backward to its staring position. How I do that?

Pelvic answered 5/3, 2010 at 13:14 Comment(0)
L
14

For simply moving the cursor to the beginning of the current line, you may print "\r", which does just that. Notice that it does not erase the old text, so be careful to either overwrite it or to clear with an ANSI code.

On systems using ANSI/VT control codes, you can print "\033[1;2H" to position the cursor. It will move the cursor and will not print anything on screen. The values 1 and 2 are the row and the column, so change them to use different positions.

There are also other codes for colors and other things: http://bluesock.org/~willg/dev/ansi.html

Notice that none of these codes are portable and they may not work on all systems (most notably they don't work by default on some Microsoft systems). Non-supporting systems will instead display some garbage on screen (the code itself).

Laborious answered 5/3, 2010 at 13:19 Comment(2)
Do you know how to increase row number in loop eg: for (i = 1; i < 10; i++){ printf("\033[i;1H text in row %d, i); } (it does not work, so should i escpae 'i' ? or maybe its another way to do it ? ?Pelvic
"Non-supporting systems will instead display some garbage on screen (the code itself)" — which is the case of the Go Playground itself! But on ANSI/VT terminals, it works great!Code
F
9

write a \r

while(1) {
 printf("\rDate and Time are %s      ", asctime(localtime(&current)) );
 fflush(stdout);
}
Feeding answered 5/3, 2010 at 13:17 Comment(0)
B
1

\r does not work on windows terminals. I know because i just tried. It gets interpreted as carriage return, line feed. There might be a setting to change that but I don't know what it is.

I wish there was an easy way to know what your current line was. I have a process that takes some time and I want to print out the progress like 1 of 2000, 2 of 2000 in place instead of having 2000 lines printed. 😁

Bandbox answered 28/3, 2023 at 17:36 Comment(0)
P
0

It might work to print a "\r" at the start of the line.

Pyjamas answered 5/3, 2010 at 13:16 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.