How do I clear the screen in C? [duplicate] - c

This question already has answers here:
Clearing output of a terminal program Linux C/C++
(7 answers)
Clear screen in C and C++ on UNIX-based system?
(10 answers)
Closed 9 years ago.
I want to clear all the text that is on the screen.
I have tried using:
#include <stdlib.h>
sys(clr);
Thanks in advance!
I'm using OS X 10.6.8. Sorry for the confusion!

You need to check out curses.h. It is a terminal (cursor) handling library, which makes all supported text screens behave in a similar manner.
There are three released versions, the third (ncurses) is the one you want, as it is the newest, and is ported to the most platforms. The official website is here, and there are a few good tutorials.
#include <curses.h>
int main(void)
{
initscr();
clear();
refresh();
endwin();
}

The best way to clear the screen is to call the shell via system(const char *command) in stdlib.h:
system("clear"); //*nix
or
system("cls"); //windows
Then again, it's always a good idea to minimize your reliance on functions that call the system/environment, as they can cause all kinds of undefined behavior.

Windows:
system("cls"); // missing 's' has been replaced
Unix:
system("clear");
You can wrap this in a single, more portable piece of code like so:
void clearscr(void)
{
#ifdef _WIN32
system("cls");
#elif defined(unix) || defined(__unix__) || defined(__unix) || (defined(__APPLE__) && defined(__MACH__))
system("clear");
//add some other OSes here if needed
#else
#error "OS not supported."
//you can also throw an exception indicating the function can't be used
#endif
}
Note the check for unix is pretty expansive. This should also detect OS X, which is what you're using.

The availability of this function or similar ones like clrscn() are very system dependent and not portable.
You could keep it really simple and roll you own:
#include <stdio.h>
void clearscr ( void )
{
for ( int i = 0; i < 50; i++ ) // 50 is arbitrary
printf("\n");
}

Related

The function _getch() behaves unexpectedly in git-bash terminal

I have been trying to figure out how it is possible to change the terminal's mode from "cooked" to "raw" using C and in a Git Bash terminal.
I have tried to execute the program with winpty and that makes that certain part of the program function as expected. However, it messes up the other parts, like clearing the screen with the control sequence \x1b[2J, and vice versa. Clearing the screen works perfectly when I am NOT executing the program with winpty.
I have also tried using system("clear") and system("cls") but with no luck. I have also tried to set the mode using the function _setmode(_fileno(stdin), _O_BINARY) but no such function seems to be working with Git Bash and more specifically MinTTY.
When I am using getch() nothing simply happens and I have to use CTRL+C to exit the program. However, it should exit the program when I press the 'i' character.
The code looks like this:
#include <windows.h>
#include <conio.h>
#include <stdio.h>
void clear_screen() {
printf("\\033\[2J");
printf("\\033\[1;1H");
fflush(stdout);
}
int main() {
#ifdef _WIN32
clear_screen();
while (1) {
char c = _getch();
if (c == 'i') {
exit(0);
}
}
#endif
#ifdef linux
#endif
}

When should I use preprocessor directives over if statements

I am sorry if this sounds like a dumb question, I am learning C, and I was wondering: when should I prioritize this syntax, for example
#include <stdio.h>
#define ALIVE 1
int main(void) {
#if ALIVE
printf("Alive");
#else
printf("Unalived");
#endif
}
Over this syntax (example):
#include <stdio.h>
#define ALIVE 1
int main(void) {
if (ALIVE)
printf("Alive");
else
printf("Unalived");
}
Thank you for spending time reading my question, I hope this isn't a dumb question and I wish you a nice day.
For starters, and to see the main difference between the two programs you show, let's see how they will look after preprocessing.
The first one:
#include <stdio.h>
#define ALIVE 1
int main(void) {
#if ALIVE
printf("Alive");
#else
printf("Unalived");
#endif
}
will expand to
#include <stdio.h>
int main(void) {
printf("Alive");
}
The second one:
#include <stdio.h>
#define ALIVE 1
int main(void) {
if (ALIVE)
printf("Alive");
else
printf("Unalived");
}
will expand to:
#include <stdio.h>
int main(void) {
if (1)
printf("Alive");
else
printf("Unalived");
}
[Examples above skip the actual inclusion of the header file]
While this doesn't directly answer your question it can give hints to what using the preprocessor conditional compilation for.
The main use is to conditionally give the compiler different code depending on the macros. Mostly used for portability-issues, when creating programs that needs to be built for different systems (for example Linux and Windows).
When using the preprocessor to do conditional compilation, whole parts of the code, that would otherwise be invalid on the target system, could simply be omitted and the compiler won't even see it.
If you use the standard C if statement, then both branches of the condition must be valid code that the compiler can build.
As a rule of thumb, you should always prefer if (... over #if and should only use #if where if will not work
when there's something in the if that is syntactically incorrect when the condition is false so it won't compile at all
when you need to do this at the global scope, where statements (like if) are not allowed
in your example, the if version is much better.

Tons of error in Visual Studio 2017 with GetUserNameEx at compile time [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 5 years ago.
Improve this question
I am trying to use GetUserNameEx, but cannot even compile it because I got tons of errors. This is my code:
#include <Windows.h>
#include <Secext.h>
#include <tchar.h>
#include <wchar.h>
#pragma comment(lib, "Secur32.lib")
int wmain(int argc, WCHAR *argv[])
{
//GetUserNameEx()
EXTENDED_NAME_FORMAT nameFormat = NameDnsDomain;
WCHAR nameExtended[256 + 1];
DWORD sizeExtended = 256 + 1;
if (GetUserNameEx(nameExtended, &sizeExtended))
{
wprintf(L"%s\n", nameExtended);
}
else
{
wprintf(L"Error code: %lu\n", GetLastError());
}
return 0;
}
These are the errors I am getting when trying to compile:
Can you help me? Seems like the compiler could not recognize that function.
Edit: I cannot include all the errors because there are around 48 has nothing to do with the code, except for the wrong function calling.
You are including the wrong header. The documentation usually contains two pieces of information regarding headers: The header file that declares a symbol, as well as the header file you are supposed to #include.
From the Requirements section:
Header: Secext.h (include Security.h)
To solve the issue, replace
#include <Secext.h>
with
#include <Security.h>
It is important to always include the header file you are told to. Header files often change the environment, and when you try to include the header that declares a symbol directly, all sorts of odd things can happen.
You also have a bug in your call, passing the wrong arguments. It should be this instead:
WCHAR nameExtended[256 + 1];
ULONG sizeExtended = 256 + 1;
if (GetUserNameExW(NameDnsDomain, nameExtended, &sizeExtended)) {
// ...
Compiling this produces the following error:
fatal error C1189: #error: You must define one of SECURITY_WIN32, SECURITY_KERNEL, or
(The trailing SECURITY_MAC is missing, due to wrong formatting in a system header.)
To fix this, #define the preprocessor symbol SECURITY_WIN32 (for user-mode applications1) prior to including <Security.h>, either in code or through the project settings, e.g.:
#define SECURITY_WIN32
#include <Security.h>
1 There is very little information regarding those preprocessor symbols. The most enlightening comment is from <NTSecPKG.h> reading // Can't use the windows.h def'ns in kernel mode. inside an #ifdef SECURITY_KERNEL conditional. SECURITY_MAC is likely from those days, when MFC was still meant to be a cross-platform framework, targeting Windows as well as "Classic" Mac OS. It is of no practical use today.
Two problems:
There seems to be a define issue regarding SEC_ENTRY. I believe it's meant to defined as __stdcall. I'm still researching this. It's actually resolved by including <sspi.h> first and defining a security model.
Regardless, the call to GetUserNameEx is incorrect.
Instead of this:
if (GetUserNameEx(nameExtended, &sizeExtended))
It should be this:
if (GetUserNameEx(nameFormat, nameExtended, &sizeExtended))
Adjusted code:
#define SECURITY_WIN32
#include <Windows.h>
#include <sspi.h>
#include <secext.h>
#include <stdio.h>
#pragma comment(lib, "Secur32.lib")
int wmain(int argc, WCHAR *argv[])
{
//GetUserNameEx()
EXTENDED_NAME_FORMAT nameFormat = NameDnsDomain;
WCHAR nameExtended[256 + 1] = {};
DWORD sizeExtended = ARRAYSIZE(nameExtended);
if (GetUserNameEx(nameFormat, nameExtended, &sizeExtended))
{
wprintf(L"%s\n", nameExtended);
}
else
{
wprintf(L"Error code: %lu\n", GetLastError());
}
return 0;
}

Sleep | warning implicit declaration of function `sleep'?

I am learning C.
In this program
I use sleep function to slowdown a count down.
My text book doesn't specify a library I should include to use the sleep function.
So I use it without including any special library for it and it works.
But it gives me this warning message in codeblocks.
I tried to include <windows.h> but still the same warning message appears.
warning D:\Project\C language\trial8\trial8.c|19|warning: implicit
declaration of function `sleep'|
And here is my code.
#include <stdio.h>
int main()
{
int start;
do
{
printf("Please enter the number to start\n");
printf("the countdown (1 to 100):");
scanf("%d",&start);
}
while(start<1 || start>100);
do
{
printf("T-minus %d\n",start);
start--;
sleep(3000);
}
while(start>0);
printf("Zero!\n Go!\n");
return(0);
}
I want to know what does the warning message mean? How important is it? Is there anything that I should do about it? Note that the program works anyway.
The issue is in the libraries (header files):
on Windows:
#include <windows.h> and Sleep(1000); => 1000 milliseconds
on Linux:
#include <unistd.h> and sleep(1); => 1 second
The function sleep is not part of C programming language. So, C compiler needs a declaration/prototype of it so that it can get to know about about number of arguments and their data types and return data type of the function. When it doesn't find it, it creates an Implicit Declaration of that function.
In Linux, sleep has a prototype in <unistd.h> and in windows, there is another function Sleep which has a prototype in <windows.h> or <synchapi.h>.
You can always get away with including header, if you explicitly supply the prototype of the function before using it. It is useful when you need only few functions from a header file.
The prototype of Sleep function in C on windows is:
VOID WINAPI Sleep(_In_ DWORD dwMilliseconds);
Remember, it is always a good practice to supply the prototype of the function being used either by including the appropriate header file or by explicitly writing it. Even, if you don't supply it, compiler will just throw a warning most of the time and it will make an assumption which in most cases will be something that you don't want. It is better to include the header file as API might change in future versions of the Library.
Windows doesn't have the sleep function. Instead, it has Sleep, which takes the number of milliseconds to sleep:
VOID WINAPI Sleep(
_In_ DWORD dwMilliseconds
);
You'll need to either #include <windows.h> or #include <synchapi.h>, depending on the version of Windows you're running. See MSDN for more details.
Update in 2022:
As it is stated on the Linux man page here we need to include unistd.h and should do fine for all OS.
#include <stdio.h>
#include <unistd.h>
int main()
{
sleep(1); /* sleep for 1 second*/
printf("END\n");
return 0;
}
To make it more cross-platform, try this:
#ifdef _WIN32
#include <Windows.h>
#else
#include <unistd.h>
#endif

C puzzle: how will you print something on console?

/*you cannot change anything from here below*/
main()
{
exit(0);
}
/*you cannot change anything from here up*/
This was asked during an interview.
I was told to print something on console.
anybody?
Really surprised that nobody posted this yet:
#include <stdio.h>
#if 0
/*you cannot change anything from here below*/
main()
{
exit(0);
}
/*you cannot change anything from here up*/
#endif
int main()
{
printf("Hello, World!");
return 0;
}
Prints at runtime and no undefined behavior whatsoever.
weird question...
int main(void)
{
printf("hello");
return 0;
}
#define main int lol
/*you cannot change anything from here below*/
main()
{
exit(0);
}
/*you cannot change anything from here up*/
#include <stdio.h>
#define exit(c) return puts("foobar"),0
over main
One implementation defined way would be to use the pragma directives to print during compilation.
#pragma message "Compiling " __FILE__ "..."
Or, you could do this with some macros and a printf (but not without introducing UB in some aspect or the other) at runtime.
#define exit(x) printf("Hello, world!")
int main() {
exit(0);
return 0; /* if pre-C99 */
}
#include <stdio.h>
#pragma message("Some foobar")
#error This is an error message
int main()
{
exit(0);
}
I think the interviewer wanted to know if you're aware of the #error directive ... just my 2 cents.
Most answers involve the #define c-preprocessor instruction to change what the program means. Most compilers also support something like
#pragma startup foo()
details depend on the compiler vendor. You can make code run BEFORE main(*) is called that way.
#define exit(x) (printf("Bye"))
int main(int argc,char* argv)
{
exit(0);
getchar();
return 0;
}
Solution 1.
This works without any preprocessor directives in cl and gcc, although I've not tested to make sure I'm not using any extensions:
#include <stdio.h>
static void exit() {
printf("Hello world");
}
/*you cannot change anything from here below*/
main()
{
exit(0);
}
/*you cannot change anything from here up*/
I think it's valid but I can't remember if masking a standard library function is allowed or not.
Solution 2
As several other answers have specified, you can use preprocessor directives, eg:
#define main or exit to be something that calls ifdef
use #if 0 to prevent the existing code being compiled
using #pragma message or #error to print a message at compile time
using #pragma startup to use a different function as main or to run start-up code before main.
Solution 3
If your compiler supports any C++ features in addition to C, there are many answers:
Declare a class with a constructor and a static variable of that type
Put the existing "main" function into a separate namespace (or class definition) and write a different global main
Solution 4
I also looked for any way of forcing a run-time error (stack overflow, out of memory, null dereference, tc), which would normally cause the program to print something, but couldn't find any way that didn't involve running extra code, in which case the extra code might as well be printf.
If you interpreted the question to mean you could not or were not allowed to edit the file by commenting out /* */ or using #ifdef _COMMENT_ME_OUT__ #endif respectively above and below the section you are not allowed to edit and then introducing a new main, then you should give an answer of using another .c file.
If you cannot find a workaround to edit that file, then use a different c file.

Resources