I'm new to C and I do not own a mac, but I'm working on a personal project for someone who does and part of the project's requirements is that it clears the screen. The reason I need to clear the screen is that it's part of a loop that clears the screen and then prints something again (I'm trying to make a "ticking counter" of sorts.)
I know that system("cls") works well on my terminal (obviously any system function isn't ideal though), however, I know that she's on a Mac OS, and that the system() function is notoriously nonportable and I need this to work on a mac. I've scoured the internet trying to see what system functions clear the screen on a mac, and the most recent source I could find was from 2006. Considering how often the mac gets updated, I'm not surprised that
I don't really need a solution that's elegant or secure, just an idea for something that works. My compiler is MinGW with GCC for libraries.
Here's a sample of the relevant code:
#include <stdio.h>
#include <time.h>
#include <math.h>
#include <unistd.h>
#include <stdlib.h>
#include <string.h>
#include <conio.h>
int main()
{
time_t seconds; //variable declarations
float days;
float rate;
int i;
i = 3;
char str[50];
while (i > 2);
{
time(&seconds);
days = (seconds - ((float)1584673594)) / (float)86400;
rate = pow(1.05, days);
rate = rate * 100;
printf("\nCurrent Snuggle-Debt Balance: %f snuggles\n", rate);
printf("Days passed: %f \n", days);
sleep(.5);
system("cls");
If you're writing a C program that uses standard input and output, and you need to do things like move the cursor around or clear part or all of the screen, the curses library is what you want. Curses is widely available and does what you want and much more. To clear the screen, just call the clear() function. And that's just the beginning of what you can do.
Related
Hello I've been trying to experience cache miss and hits in Linux.
To do so, I've done a program in C, where I mesure the time in CPU cycle to do the instruction printf(). The first part mesure the time needed for a miss and the second one for a hit. Here is the given program :
#include <stdint.h>
#include <stdio.h>
#include <string.h>
#include <sched.h>
#include <sys/types.h>
#include <unistd.h>
#include <signal.h>
uint64_t rdtsc() {
uint64_t a, d;
asm volatile ("mfence");
asm volatile ("rdtsc" : "=a" (a), "=d" (d));
a = (d<<32) | a;
asm volatile ("mfence");
return a;
}
int main(int argc, char** argv)
{
size_t time = rdtsc();
printf("Hey ");
size_t delta1 = rdtsc() - time;
printf("delta: %zu\n", delta1);
size_t time2 = rdtsc();
printf("Hey ");
size_t delta2 = rdtsc() - time2;
printf("delta: %zu\n", delta2);
sleep(100);
}
Now I would like to show that two processes (two terminals) have cache in commun. So I thought that running this program in two terminals would result in :
Terminal 1:
miss
hit
Terminal 2:
hit
hit
But now I have something like:
Terminal 1:
miss
hit
Terminal 2:
miss
hit
Is my understanding incorrect? Or my program wrong?
Your assumption is somewhat correct.
printf is part of the libc library. If you use dynamic linking, the operating system may optimize memory usage by only loading the library once for all processes using it.
However, there are multiple reasons why I don't expect you to measure any sizable difference:
compared to the difference between a cache hit and cache miss, printf takes an enormous amount of time to complete and there is a lot going on that introduces noise. With just a single measurement, it is very unlikely that you're able to measure that tiny difference.
the actual reason for the first measurement to take longer is likely the lazy binding of the library function printf being resolved by the loader (https://maskray.me/blog/2021-09-19-all-about-procedure-linkage-table) or some other magic happening (buffers being setup, etc.) for the first output.
a lot of libc functions are used by many different processes. If the library is shared, it is likely, that printf may be cached even though you did not use it.
I would suggest to mount a Flush+Reload attack (https://eprint.iacr.org/2013/448.pdf) on printf in one of the terminals and use it in the other terminal. Then, you may see a timing difference.
Note: to find the actual address of printf for the attack, you need to be familiar with dynamic linking and the plt. Just using something like void* addr = printf will probably not work!
I am new and I know how to color output only in Unix/Linux systems:
#include <stdio.h>
int main(void) {
printf("\033[1;31mRed Message\033[0m.");
}
But this is not works in Windows cmd.exe, only in Unix terminal.
I am writing cross-platform app and want to know how can I do this in Windows cmd.exe too.
This also does not works:
1.
#include <stdio.h>
int main(void) {
printf("%c[1;31mRed Message%c[0m", 27, 27);
}
2.
#include <stdio.h>
int main(void) {
printf("[1;31m Red Message [0m");
}
This works, but I think this is just a bug:
If I type system(""); before printf then it works.
#include <stdio.h>
int main(void) {
system("");
printf("\033[1;31m Red Message \033[0m");
}
Thanks
If you want to make your library crossplatform, I would use the following approach:
Have a library, with the same functions, let's say:
void printInRed(const char* string). (In a headerfile)
After that you write two or more implementations.
One for windows:
//TODO: Errorchecking
void printInRed(const char* string){
HANDLE hConsole = GetStdHandle(STD_OUTPUT_HANDLE);
//TODO: Extract magic number
//See https://stackoverflow.com/a/4053879/13912132
SetConsoleTextAttribute(hConsole, 12);
puts(string);
}
And another one for unix-like OS:
//TODO: Errorchecking
void printInRed(const char* string){
printf("\033[1;31m%s\033[0m.", string);
}
Then you can check at compile time, which version to compile.
The first approach is to use #ifdefs, but this will make the code a bit messy.
Another approach would be to use a build-system like CMake to select at build time, which one to build. A buildsystem requires a bit of learning, but will help you to make maintaining a crossplatform library simpler.
I had installed ncurses library in Linux mint and still I can't use getch function in c. I am using Linux mint 18.2.
Here is my program:
#include <stdio.h>
#include <curses.h>
int main() {
char k;
printf("how are you");
k = getch();
printf("%c",k);
}
and here is the output:
ram#ram$ gcc-7 test.c -lcurses
ram#ram$ ./a.out
how are you�ram#ram$
It does't wait for me to press any key and terminate to quickly. I don't want to install conio.h for Linux. How can I use getch and getche function in Linux? Please don't tell me to make my own function. I am still a noob. Or there must be alternatives.
Here's a "corrected" version, explaining what's wrong in the comments:
#include <curses.h>
#include <stdio.h>
int main(void)
{
// use the correct type, see https://linux.die.net/man/3/getch
int k;
// init curses:
initscr();
// in curses, you have to use curses functions for all terminal I/O
addstr("How are you?");
k = getch();
// end curses:
endwin();
printf("You entered %c\n", k);
return 0;
}
This still isn't good code, you should at least check whether you got a valid character from getch().
It's also important to note that getch() isn't a "function of C". It's part of curses, a well-known platform-independent API for console/terminal control, with implementations e.g. for *nix systems (ncurses) and Windows (pdcurses). It's not part of the language C.
I've done a C program that takes the RGB values (0-255) of a pixel of the screen knowing its position (x,y). It works in Linux, but when I try to compile it in Visual Studio (Windows), crashes because libraries X11/Xlib.h, X11/Xutil.h, unistd.h doesn't exist.
This is the code:
#include <X11/Xlib.h>
#include <X11/Xutil.h>
#include <stdio.h>
#include <time.h>
#include <unistd.h>
#include <stdlib.h>
void getimage(XColor c, Display* d, int* rgb, int x, int y) {
XImage* image;
image = XGetImage(d, RootWindow(d, DefaultScreen(d)),
x, y, 1, 1, AllPlanes, XYPixmap);
c.pixel = XGetPixel(image, 0, 0);
XFree(image);
XQueryColor(d, DefaultColormap(d, DefaultScreen(d)), &c);
rgb[0] = c.red / 256;
rgb[1] = c.green / 256;
rgb[2] = c.blue / 256;
}
int main () {
int rgb[3], x, y;
XColor c;
Display* d = XOpenDisplay((char*)NULL);
getimage(c, d, rgb, x, y);
}
How can I implement this to run in Windows?
You've written an X11 program. X is the consensus standard for graphical displays on UNIX-like systems other than OS X (but it is also freely available for OS X).
Windows uses a completely different graphical display API. It is conceivable that you could find an X implementation that runs on Windows, but Microsoft certainly doesn't provide one. Since your program is quite short, your best bet is probably to rewrite it using the Windows API.
As for unistd.h (and time.h), I don't see anything in your program that depends on it. If you weren't going to rewrite the program, you could resolve that part of your problem simply by removing the offending #include statement.
One small part to the answer for your question may be to search around MSDN. The following function is described there: (link below)
#include <Windows.h>
...
DWORD WINAPI GetSysColor(
_In_ int nIndex
);
To use that function, you must link to User32.lib which is implemented in User32.dll
The descriptions of GetSysColor(...) et. al. are accessible here. This function is one of many that support similar functionality, but warning, the usage methods will be like a completely different language. Windows programming is rarely similar to Linux programming.
Other starting points to Windows related graphical/image programming:
capturing an image
Create your own Snipping tool
I have very simple code that should run on background and at 1 am shut down the computer:
#include <ctime>
#include <cstdlib>
#include <unistd.h>
int main() {
time_t t;struct tm * now;
daemon(0,0);
while(1){
t = time(0);
now = localtime( & t );
if(now->tm_hour==1){
system("shutdown -P");
break;
}
sleep(10);
}
return 0;
}
The code works without sleep(10) but uses whole free memory so I need sleep function there to stop loop and recheck time each ten seconds, but with sleep function program stops immediately after I run it.
If you are writing C code, don't use C++ headers (ctime, cstdlib). Replace those #includes with #include <stdlib.h> and #include <time.h>. If the behavior of this code is really as you describe (which I would find surprising), then this is probably the source of the error.
Of course it immediately exits. Thats the whole point of using daemon. Check with ps and you will see that your proram is still running as a seperate process now.
Check the man page for a desription how daemon works.