Silly question but,
Is it possible to break a line on stdout without the line feed using printf();? If not, any tips on how I would overwrite 2+ lines, if possible?
I'm trying to generate sort of a progress bar but on multiple lines.
Any ideas?
EDIT:
So yeah I accepted the below answer although it won't work for my specific case.
I'm trying to overwrite 2+lines
rather than a single line.
printf("12345\r");
fflush(stdout);
printf("67890\n");
The result of which is $ ./a.out 67890
But what I'm trying to achieve is have 2+ lines be overwritten with new data.
Similar to a progress bar but on 2+ lines except I have a percentage number for some data.
To rewrite all (or part) of a line, you need to use the correct number of backspace characters. Eg:
printf("some text");
printf("\b\b\b\bstuff");
Will output:
some stuff
This is fine for simple stuff; for something more complex you should use ncurses which uses ANSI-escape cleverness to manipulate the cursor around the screen.
If your terminal (or, much more likely, terminal emulator) supports VT100-style escape sequences, you can print specific code sequences to control the cursor position, clear some or all of the screen/window, etc.
For example, to move the cursor up 1 line:
printf("\x1b[A");
fflush(stdout);
To move the cursor up 2 lines, either do that twice or:
printf("\x1b[2A"});
fflush(stdout);
These are commonly referred to as ANSI escape codes; the link is to a Wikipedia article that lists many of them. They were first implemented by the old DEC VT-100 terminal, which is emulated by most modern terminals and emulators.
And this:
printf("\x1b[J");
fflush(stdout);
will clear part of the screen, from the current cursor position to the bottom.
These sequences should be enough to do what you need. (They might not work in a Windows command window.)
More portably, if your system supports it, you can use termcap or terminfo to determine the proper command sequences for your current terminal (as determined by the $TERM environment variable). The tput command lets you do this on the command line; man tput for more information. In practice, you're unlikely to find a system these days that supports termcap or terminfo with a terminal that's not VT100-compatible; printing raw escape sequences is strictly not portable, but probably good enough.
A suggestion: your program should probably have an option to inhibit any such control sequences; for example, if a user who wants to redirect the output to a file won't want to have those escape sequences in the file. Some programs use control sequences only if they can determine that stdout is a terminal, but an explicit option is also a good idea.
*UPDATE: *
Here's a program I threw together that demonstrates how to do this with the terminfo. It should work on just about any Unix-like system.
#include <stdio.h>
#include <stdlib.h>
#include <curses.h>
#include <term.h>
#include <unistd.h>
int main(void) {
const char *term = getenv("TERM");
if (term == NULL) {
fprintf(stderr, "TERM environment variable is not set\n");
exit(EXIT_FAILURE);
}
setterm(term);
for (int i = 0; i < 10; i ++) {
putp(tparm(clr_eos));
printf("%d\n%d\n", i, i+1);
sleep(1);
putp(tparm(parm_up_cursor, 2));
}
return 0;
}
Related
I'm new to C and I came across this code and it was confusing me:
sprintf(banner1, "\e[37╔═╗\e[37┌─┐\e[37┌┐┌\e[37┌─┐\e[37┌─┐\e[37┌─┐\e[37┌─┐\e[37m\r\n");
sprintf(banner2, "\e[37╠═╝\e[37├─┤\e[37│││\e[37│ ┬\e[37├─┤\e[37├┤\e[37 ├─┤\e[37m\r\n");
sprintf(banner3, "\e[37╩ \e[37┴ ┴┘\e[37└┘\e[37└─┘\e[37┴ ┴\e[37└─┘\e[37┴ ┴\e[37m\r\n");
I was just confused as I don't know what do \e[37 and \r\n mean. And can I change the colors?
This looks like an attempt to use ANSI terminal color escapes and Unicode box drawing characters to write the word "PANGAEA" in a large, stylized, colorful manner. I'm guessing it's part of a retro-style BBS or MUD system, intended to be interacted with over telnet or ssh. It doesn't work, because whoever wrote it made a bunch of mistakes. Here's a corrected, self-contained program:
#include <stdio.h>
int main(void)
{
printf("\e[31m╔═╗\e[32m┌─┐ \e[33m┌┐┌\e[34m┌─┐\e[35m┌─┐\e[36m┌─┐\e[37m┌─┐\e[0m\n");
printf("\e[31m╠═╝\e[32m├─┤ \e[33m│││\e[34m│ ┬\e[35m├─┤\e[36m├┤ \e[37m├─┤\e[0m\n");
printf("\e[31m╩ \e[32m┴ ┴┘\e[33m┘└┘\e[34m└─┘\e[35m┴ ┴\e[36m└─┘\e[37m┴ ┴\e[0m\n");
return 0;
}
The mistakes were: using \r\n instead of plain \n, leaving out the m at the end of each and every escape sequence, and a number of typos in the actual letters (missing spaces and the like).
I deliberately changed sprintf(bannerN, ... to printf to make it a self-contained program instead of a fragment of a larger system, and changed the actual color codes used for each letter to make it a more interesting demo. When I run this program on my computer I get this output:
The program will only work on your computer if your terminal emulator supports both ANSI color escapes and printing UTF-8 with no special ceremony. Most Unix-style operating systems nowadays support both by default; I don't know about Windows.
I am trying to create a minigame to play with my friends, where someone puts a number, and then we have 10 tries to guess it. Unfortunately, we a number is scanned, it stays in the terminal, so everyone can read and cheat.
I also tried to do something kinda dumb, which was use printf("\n\n\n\n\n\n\n\n\n\n\n\n\n...") with 29, but that way the code goes down and looks bad.
Can anyone help me?
You didn't specify the platform (OS).
In General there are several methods:
Supressing echo via stty(): See https://stackoverflow.com/a/67709009/6607497
Using getpass() (obsolete)
Use terminal escape sequences (like ANSI) to Query the input at a specific line, then erase that line. See https://en.wikipedia.org/wiki/ANSI_escape_code for details.
Learn to use curses. See http://heather.cs.ucdavis.edu/~matloff/UnixAndC/CLanguage/Curses.pdf for details
How to disable echo in windows console?
ANSI C No-echo keyboard input
https://www.reddit.com/r/C_Programming/comments/64524q/turning_off_echo_in_terminal_using_c/
https://social.msdn.microsoft.com/Forums/en-US/14220ac4-a557-4cea-b29d-f46222a36ef5/how-to-not-echo-the-input-of-consoleread
http://www.cplusplus.com/forum/general/3570/
https://falsinsoft.blogspot.com/2014/05/disable-terminal-echo-in-linux.html
...
Maybe you should have searched elsewhere first!
Probably the simplest thing (but certainly not the best)you can do is shell out to stty to manipulate the terminal database. Eg:
#include <stdio.h>
#include <stdlib.h>
int
main(void)
{
char b[32];
printf("prompt: ");
system("stty -echo"); /* Turn off echo */
if( scanf("%31s", b) == 1 ){
printf("\nyou entered %s\n", b);
}
system("stty echo"); /* Turn echo back on */
return 0;
}
Note that this does not handle signals well, and your terminal may end up with a modified state.
If you use windows, you can specifies the maximum number of commands in the history buffer.:
system("doskey /listsize = 0");
In addition, You can simulate the keyboard shortcut ALT+F7 to clear the history.
See more for windows.
If you use Unix, you can clean the history:
system("history -c");
if you #include <stdlib.h>, system("cls"); should clear the terminal after the number is entered. I tried the game, its fun!
I'm trying to reposition the text-cursor to top left corner of the console each frame, so the resulted square rendered at the same position
#include <stdio.h>
#include <stdlib.h>
int main() {
while(1) {
printf("\u2554\u2550\u2550\u2550\u2557\n\u255A\u2550\u2550\u2550\u255D\n");
}
}
I found that this is possible in windows by including <windows.h>:
HANDLE hOut;
COORD Position;
hOut = GetStdHandle(STD_OUTPUT_HANDLE);
Position.X = 0;
Position.Y = 0;
SetConsoleCursorPosition(hOut,Position);
How can I do that in Ubuntu?
[update] Oops, sorry, I didn't notice the "[C]" tag and my answer was only referring to shell commands.
The actual answer is to use a curses-like library, like ncurses.
For example, the function you are looking for is typically move().
Original answer:
On Unix systems, moving the cursor depends on the type of the terminal you are using.
There are libraries like ncurses that aim to provide functionalities that are terminal-independent. tput is a command that uses ncurses to make some terminal capabilities (like moving the cursor) available to the command line:
tput cup 0 0
will put the cursor in the (0,0) position, whatever the terminal you are using (if such a terminal allows you to move the cursor)
Write \033[H to the console, and this will put the cursor in the top left corner of the terminal.
For that, the terminal must be ANSI compatible (for example, the xterm terminal or the linux console)
Anyway, I recommend you to use the ncurses library, which gives you many possibilities, apart of this, and in a manner that is terminal type independent (so it will run in almost any known terminal type, e.g. an hp terminal)
I need to create a interface in terminal using the termios.h in C. To keep it short I have to create a executable like ./exec and after I run, it has to stop displaying the PS1 variable.
If I have a program which displays the following text Hello World that uses printf it will look like:
$:> ./exec
Hello World!
But instead of printing that, I need only the Hello World! to be in the terminal, like when you clear the screen while the program is displaying.
Hello World!
To say it in other way, the purpose is to clean the terminal, and when the ./exec is runned, it should clear this line as well, $:> ./exec.
So far I managed to make this function
void clear_screen()
{
char buf[1024];
char *str;
tgetent(buf, getenv("TERM"));
str = tgetstr("cl", NULL);
fputs(str, stdout);
}
Which clears the screen but it keeps the line with the command itself $:> ./exec. I am not allowed to use ncurses.h library.
Here is a main:
int main(void)
{
clear_screen();
printf("Hello World!\n");
return (0);
}
Something was omitted from the question (and it confuses termcap with termios). Since the sample code uses termcap, answers should address that. To recap, here's a complete example:
#include <stdio.h>
#include <stdlib.h>
#include <termcap.h> /* this comes from ncurses, anyway... */
static void clear_screen(void)
{
char buf[1024];
char *str;
tgetent(buf, getenv("TERM"));
str = tgetstr("cl", NULL);
fputs(str, stdout);
}
int main(void)
{
clear_screen();
printf("Hello World!\n");
return (0);
}
The "cl" capability is what matters. It is defined as the corresponding feature to terminfo clear:
clear_screen clear cl clear screen and
home cursor (P*)
If you run that example from the command-line with a correctly written terminal description, the output does this:
clear the entire display,
move the cursor to the home-position
print a message (which would be on the first line of the screen)
exit
After that, the shell prints its prompt again.
There's a couple of problems with the example:
it is using fputs for output. terminfo/termcap data could include padding, which won't work with that. You won't notice that with common terminal emulators' terminal description, but it matters for hardware terminals. The vt100 termcap would have this, for instance (the "50" is padding):
:cl=50\E[H\E[J:
The proper function to use would be tputs. It happens to be in an overlapping set of functions between termcap and terminfo. In ncurses, the complete description is in the terminfo manual page.
some terminals (Microsoft telnet used to be a good example, though no one's tested recently...) didn't treat the control sequence properly. IN the previous example, one might have used
:cl=\E[J\E[H
to demonstrate this: the terminal didn't clear the whole screen, but only the remainder. To work around this, the terminal descriptions were modified to move the cursor first.
printf("\033[2J"); // clear screen
printf("\033[H"); // cursor home
If you want to do anything with the screen, this is one way. You can look up other codes from 'some programmer dude's comment. You can also google vt100 codes.
There are libraries that abstract this like Ncurses but since you can't use that (why?) that's out - I'll let others elaborate on that though, maybe there are others that are allowed..
edit
try this:
printf("\033[1A\r\033[2K");
See my comment.
the VT100 codes don't help either
If you want to do anything with the screen vt100 codes are like a hacker's dream come true. Run, if you see the DEA coming, they are that good.
How can I change the font size of a printed font using c?
printf ("%c", map[x][y]);
I want to print an array larger than all the other text in the program. Is there a way to just make that statement print larger?
Although teppic's answer to use system() will work, it is rather intensively heavy-handed to call an external program just to do that. As for David RF' answer, it is hard-coded for a specific type of terminal (probably a VT100-compatible terminal type) and won't support the user's actual terminal type.
In C, you should use terminfo capabilities directly:
#include <term.h>
/* One-time initialization near the beginning of your program */
setupterm(NULL, STDOUT_FILENO, NULL);
/* Enter bold mode */
putp(enter_bold_mode);
printf("I am bold\n");
/* Turn it off! */
putp(exit_attribute_mode);
Still, as teppic notes, there is no support for changing the font size. That's under the user's control.
If you are under some unix, you can try to activate and deactivate bold text:
printf("\033[1m%c\033[0m", map[x][y]);
If it's Linux (and probably other forms of Unix) you could mess around with system to change a few terminal settings to make it stand out - though not the font size. This kind of thing would really only be suitable for simple programs, and it's obviously not portable:
#include <stdio.h>
#include <stdlib.h>
[...]
printf("Normal text\n");
system("setterm -bold on");
printf("Bold text\n");
system("setterm -bold off");
Otherwise there are various terminal sequences you can send directly via printf that will control most Unix terminal applications, e.g. \033[31m will change the text to red in an xterm. But these sequences can vary.
This code will work on Win32 applications (regardless of the subsystem used: WINDOWS or CONSOLE):
inline void setFontSize(int a, int b)
{
HANDLE hStdOut = GetStdHandle(STD_OUTPUT_HANDLE);
PCONSOLE_FONT_INFOEX lpConsoleCurrentFontEx = new CONSOLE_FONT_INFOEX();
lpConsoleCurrentFontEx->cbSize = sizeof(CONSOLE_FONT_INFOEX);
GetCurrentConsoleFontEx(hStdOut, 0, lpConsoleCurrentFontEx);
lpConsoleCurrentFontEx->dwFontSize.X = a;
lpConsoleCurrentFontEx->dwFontSize.Y = b;
SetCurrentConsoleFontEx(hStdOut, 0, lpConsoleCurrentFontEx);
}
Then just call (for example):
setFontSize(20,20);