How can i clearscreen in a while loop, in C programming? [duplicate] - c

I want to know: how to clean screen on an UNIX-based system? I searched on the Internet, but I've just found how to do it on Windows: system("CLS")
I don't want exactly to clean cpmpletely the screen, but I want to open a "new page", such as in the NANO and VI editors. Thanks

Maybe you can make use of escape codes
#include <stdio.h>
#define clear() printf("\033[H\033[J")
int main(void)
{
clear();
return 0;
}
But keep in mind that this method is not compatible with all terminals

You can use the following code which use termcap for clear screen.
(don't forget to link with the library)
#include <stdio.h>
#include <stdlib.h>
#include <termcap.h>
void clear_screen()
{
char buf[1024];
char *str;
tgetent(buf, getenv("TERM"));
str = tgetstr("cl", NULL);
fputs(str, stdout);
}

#include <stdlib.h>
int main(void)
{
system("clear");
}

Portable UNIX code should be using the terminfo database for all cursor and screen manipulation. This is what libraries like curses uses to achieve its effects like windowing and so forth.
The terminfo database maintains a list of capabailities (like clear which is what you would use to clear the screen and send the cursor to the top). It maintains such capabilities for a wide range of devices so that you don't have to worry about whether you're using a Linux console or a (very dated) VT52 terminal.
As to how you get the character streams for certain operations, you can choose the time-honored but rather horrible method of just using system to do it:
system ("tput clear");
Or you can capture the output of that command to a buffer so later use involve only outputting the characters rather than re-running the command:
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
static char scrTxtCls[20]; static size_t scrSzCls;
// Do this once.
FILE *fp = popen ("tput clear", "r");
scrSzCls = fread (scrTxtCls, 1, sizeof(scrTxtCls), fp);
pclose (fp);
if (scrSzCls == sizeof(scrTxtCls)) {
actIntelligently ("you may want to increase buffer size");
}
// Do this whenever you want to clear the screen.
write (1, cls, clssz);
Or, you can link with ncurses and use its API to get whatever capabilities you want, though this might drag in quite a bit of stuff for something as simple as clearing the screen. Still, it's an option to be considered seriously since it gives you a lot more flexibility.

It is usually not a matter of just clearing the screen, but of making a terminal aware application.
You should use the ncurses library and read the NCURSES programming HowTo
(You could perhaps use some ANSI escape codes as David RF answered, but I don't think it is a good idea)

You can achieve this using CSI sequences:
#include <stdio.h>
int main()
{
printf("\x1b[H\x1b[J");
}
What does \x1b[H?
Actually it is the same as \x1b[1;1;H, it means that it will move the cursor to row 1 and column 1.
What does \x1b[J a.k.a \x1b[0;J?
If n is 0 or missing, it will clear from cursor to end of screen.
Source: https://en.wikipedia.org/wiki/ANSI_escape_code#CSI_sequences

Just use #include<stdlib.h> after #include<stdio.h>.
Then you can use the command system("clear");after main() {
i.e:
#include<stdio.h>
#include<stdlib.h>
int main()
{
system("clear");
After these commands you can continue with your program.
Hope this helps :)

To clear the screen using termcaps, use this :
write(1, tgetstr("cl", 0), strlen(tgetstr("cl", 0)));

Use system("clear"); with header #include <stdlib.h> (for C Language) or #include <cstdlib> (for C++).

This code is for clear screen with reset scrollbar position in terminal style windows
#include <iostream>
int main(){
std::cout << "\033c";
return 0;
}

Related

Better way to discard output from function tested by glib test

If i test functions with glib's testharness, I always face the ugly fact, that the output of the functions I'm testign is mixed with the output of glib's functions.
This code:
#include <stdlib.h>
#include <glib.h>
#include <stdio.h>
#include <fcntl.h>
#include <unistd.h>
void to_test(void)
{
printf("this function is being tested");
}
void test_to_test(void)
{
to_test();
}
int main(int argc, char *argv[])
{
g_test_init(&argc, &argv, NULL);
g_test_add_func("/test", test_to_test);
return g_test_run();
}
generates:
/test: this function is being testedOK
The only solution I found was redirecting the filedescriptors of standardout/-err to /dev/null for the time the function is called and resetting them afterwards, like:
void test_to_test(void)
{
int backup, new;
new = open("/dev/null", O_WRONLY);
backup = dup(STDOUT_FILENO);
dup2(new, STDOUT_FILENO);
to_test();
fflush(stdout);
close(new);
dup2(backup, STDOUT_FILENO);
}
The output looks as intended:
/test: OK
Unfortunately this approach is 1.) ugly and 2.) POSIX specific. So my question is: Is there any other way to do this, so that the code is portable and at the same time aestetically appealing?
Thanks in advance!
Yours in neverending, beautiful, transcendetal love
floxo
This is possible using freopen and/or fdopen. There isn't a cross platform way of doing this unfortunately, luckily Windows has an fdopen equivalent which you can use (Is there a Windows equivalent to fdopen for HANDLEs?).
Note that this will only work if using stdio. It won't work if for some reason something is writing directly to the fd
As a longer term recommendation, why not use fprintf instead? and maintain a FILE* field in your structure which can be directed to custom output or wherever.

Get in which terminal column I'm writing

In my C program I would like to know where my cursor is located in terminal. For example, another program could have written something before mine and I would like to know how much space is left before the last column of the terminal, or I could not know the terminal reaction to some special sequences (like colors: I could write it but they are not showed).
Any suggestion?
Edit: it would be better avoiding over complicated solutions like ncurses (ncurses doesn't know where's the cursor directly: it computes its position).
Edit 2: I found a way to do it, but it works only in non-graphical terminals: https://www.linuxquestions.org/questions/programming-9/get-cursor-position-in-c-947833/
Edit 3: Nice code and it works well, but it uses /dev/vcsaN (same problem of Edit 2): http://dell9.ma.utexas.edu/cgi-bin/man-cgi?vcs+4
Ncurses is a big and powerful library for creating terminal-based text interfaces.
tputs is a simple low-level universal function for manipulating terminal capabilities.
Either one could serve your needs.
You could try using ncurses' getyx().
This solution is not optimal because it refers to /dev/vcsa*. Hope this could help someone else.
#include <stdlib.h>
#include <stdio.h>
#include <fcntl.h>
int main(void)
{
int fd;
char *device = "/dev/vcsa2";
struct {unsigned char lines, cols, x, y;} scrn;
fd = open(device, O_RDWR);
if (fd < 0) {
perror(device);
exit(EXIT_FAILURE);
}
(void) read(fd, &scrn, 4);
printf("%d %d\n", scrn.x, scrn.y);
exit(EXIT_SUCCESS);
}
Generally you are supposed to remember where you've left the cursor.
However, most terminals do respond to DSR; Device Status Request. By sending
CSI 6 n
you'll receive a CPR; cursor position report, in the form of
CSI Pl;Pc R
where Pl and Pc give the cursor line and column number, indexed from 1.

How to clear screen from simple C program?

#include <stdio.h>
#include <cstdlib>
rec();
main()
{
int a, fact;
char q, n, y;
printf("\nEnter any number ");
scanf("%d", & a);
fact = rec(a);
printf("Factorial value = %d\n", fact);
printf("do you want to exit.....(y/n):");
scanf("%s" ,&q);
if (q == 'n')
{
system("cls");
main();
}
else
return 0;
}
rec(int x)
{
int f;
if (x == 1)
return 1;
else
f = x * rec(x - 1);
return f;
}
I'm using code blocks but I don't know how to clear the screen. I searched then found system("cls"); within header file #include<cstdlib>, but it shows the error cstdlib: no such file of directory. What should I do ?
Change
#include <cstdlib>
to
#include <stdlib.h>
cstdlib is a C++ header file, and thus will be unusable in C.
Clearing the screen is outside the purview of a normal C program. It depends on the operating system.
For windows, you should look into conio.
For unix, look into curses or termios.
system() always launches a sub-shell which may or may not have any effect on the environment of the parent program. You do need a system-call, but not a system() call.
I didn't always know this. I once (long ago) suggested in comp.lang.c that someone should try system("exit"); to close the window around the DOS program. But that, of course, cannot work. And I was quickly advised to test my code before posting. :)
you have lots of problems in your code....
but for the specific problem, try #include <stdlib.h>
use the #include<stdlib.h> that's where the clear screen function is defined.
To use system("cls") you need the header <iostream>. This will allow all system() types to execute. Unsure if it is a C++ header file, but it works for the compiler that I use.

How do you clear the console screen in C?

Is there a "proper" way to clear the console window in C, besides using system("cls")?
printf("\e[1;1H\e[2J");
This function will work on ANSI terminals, demands POSIX. I assume there is a version that might also work on window's console, since it also supports ANSI escape sequences.
#include <unistd.h>
void clearScreen()
{
const char *CLEAR_SCREEN_ANSI = "\e[1;1H\e[2J";
write(STDOUT_FILENO, CLEAR_SCREEN_ANSI, 12);
}
There are some other
alternatives, some of which don't move the cursor to {1,1}.
Well, C doesn't understand the concept of screen. So any code would fail to be portable. Maybe take a look at conio.h or
curses, according to your needs?
Portability is an issue, no matter what library is used.
For portability, try this:
#ifdef _WIN32
#include <conio.h>
#else
#include <stdio.h>
#define clrscr() printf("\e[1;1H\e[2J")
#endif
Then simply call clrscr(). On Windows, it will use conio.h's clrscr(), and on Linux, it will use ANSI escape codes.
If you really want to do it "properly", you can eliminate the middlemen (conio, printf, etc.) and do it with just the low-level system tools (prepare for a massive code-dump):
#ifdef _WIN32
#define WIN32_LEAN_AND_MEAN
#include <windows.h>
void ClearScreen()
{
HANDLE hStdOut;
CONSOLE_SCREEN_BUFFER_INFO csbi;
DWORD count;
DWORD cellCount;
COORD homeCoords = { 0, 0 };
hStdOut = GetStdHandle( STD_OUTPUT_HANDLE );
if (hStdOut == INVALID_HANDLE_VALUE) return;
/* Get the number of cells in the current buffer */
if (!GetConsoleScreenBufferInfo( hStdOut, &csbi )) return;
cellCount = csbi.dwSize.X *csbi.dwSize.Y;
/* Fill the entire buffer with spaces */
if (!FillConsoleOutputCharacter(
hStdOut,
(TCHAR) ' ',
cellCount,
homeCoords,
&count
)) return;
/* Fill the entire buffer with the current colors and attributes */
if (!FillConsoleOutputAttribute(
hStdOut,
csbi.wAttributes,
cellCount,
homeCoords,
&count
)) return;
/* Move the cursor home */
SetConsoleCursorPosition( hStdOut, homeCoords );
}
#else // !_WIN32
#include <unistd.h>
#include <term.h>
void ClearScreen()
{
if (!cur_term)
{
int result;
setupterm( NULL, STDOUT_FILENO, &result );
if (result <= 0) return;
}
putp( tigetstr( "clear" ) );
}
#endif
A workaround tested on Windows(cmd.exe), Linux(Bash and zsh) and OS X(zsh):
#include <stdlib.h>
void clrscr()
{
system("#cls||clear");
}
Using macros you can check if you're on Windows, Linux, Mac or Unix, and call the respective function depending on the current platform. Something as follows:
void clear(){
#if defined(__linux__) || defined(__unix__) || defined(__APPLE__)
system("clear");
#endif
#if defined(_WIN32) || defined(_WIN64)
system("cls");
#endif
}
Since you mention cls, it sounds like you are referring to windows. If so, then this KB item has the code that will do it. I just tried it, and it worked when I called it with the following code:
cls( GetStdHandle( STD_OUTPUT_HANDLE ));
#include <conio.h>
and use
clrscr()
There is no C portable way to do this. Although various cursor manipulation libraries like curses are relatively portable. conio.h is portable between OS/2 DOS and Windows, but not to *nix variants.
The entire notion of a "console" is a concept outside of the scope of standard C.
If you are looking for a pure Win32 API solution, There is no single call in the Windows console API to do this. One way is to FillConsoleOutputCharacter of a sufficiently large number of characters. Or WriteConsoleOutput You can use GetConsoleScreenBufferInfo to find out how many characters will be enough.
You can also create an entirely new Console Screen Buffer and make the current one.
Windows:
system("cls");
Unix:
system("clear");
You could instead, insert newline chars until everything gets scrolled, take a look here.
With that, you achieve portability easily.
just type clrscr(); function in void main().
as example:
void main()
{
clrscr();
printf("Hello m fresher in programming c.");
getch();
}
clrscr();
function easy to clear screen.
In Windows I have made the mistake of using
system("clear")
but that is actually for Linux
The Windows type is
system("cls")
without #include conio.h
The proper way to do it is by using tput or terminfo functions to obtain terminal properties and then insert newlines according to the dimensions..
Just call this function below:
void clearScreen() {
system("clear");
}
This should work. Then just call cls(); whenever you want to clear the screen.
(using the method suggested before.)
#include <stdio.h>
void cls()
{
int x;
for ( x = 0; x < 10; x++ )
{
printf("\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n");
}
}

Is there a way to get text as soon as possible without waiting for a newline?

I'm using C. I wrote a very simpe program which prints back the input, using getchar() and putchar() or printf(). Is there any way to make it so as soon as the user types one key, the program registers it, without waiting for an Enter? Let me show:
Currently, if the user types "abc" and then presses Enter, the program prints "abc" and a newline and keeps waiting for more input. I want to make it so as soon as the user types "a", the program prints "a" and waits for more input. I'm not sure whether this has to be done inside the source code or if something has to be changed in the Windows command line.
Just in case, here's the source code:
#include <stdio.h>
int main()
{
int c;
while ((c = getchar()) != EOF) {
putchar(c);
}
return 0;
}
if you are using Visual Studio, there is a library called conio (#include <conio.h>) which defines a kbhit() function and getch().
otherwise, on Windows, there is still the possibility of using functions from the Windows SDK (ReadConsoleInput() and the like), but that would require a little bit more code (although, once done and if done properly, it can be reused any time you want)
If you're using Visual Studio, you can use getch().
In this simple case, the other answers should suit you fine.
The general solution is to disable line buffering. This depends on the particular console; the following example is Windows-only (untested):
#include <windows.h>
int main() {
HANDLE hConsole = GetStdHandle(STD_INPUT_HANDLE);
DWORD mode;
GetConsoleMode(hConsole, &mode);
SetConsoleMode(hConsole, mode & ~ENABLE_LINE_INPUT);
// ...
}
I assume that the standard C library functions are implemented in terms of ReadConsole and friends; if not, this might not even work. (I'm currently on Linux, so I cannot test this.)
On Linux you can take over the terminal:
#include <stdio.h>
#include <ctype.h>
#include <termios.h>
system("stty raw"); /* raw output to terminal, direct feedback */
system("clear"); /* clear screen */
printf("Press a key");
answer = getchar();
system("stty cooked"); /* revert back*/

Resources