Which gotoxy() function should I use? - c

during this year in school my teacher showed us this function:
#include<Windows.h>
void gotoxy(int x,int y)
{
COORD punto;punto.X=x;punto.Y=y;
SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE),punto);
}
And looking in here some posts I read about this one based on ANSI escape codes
#include<stdio.h>
void gotoxy(int x, int y)
{
// <ESC>[(ROW);(COLUMN)f
printf("\x1B[%i;%if",y,x);
}
I kind of like the second one more, I feel I understand it better. But I wanted to ask here which of them is better because I know I'm probably missing something. What do you think?

If you write code for Windows then definitely use the first version. It always works on Windows but it does not work on other OSes (it does not even compile because other OSes do not provide these functions).
The second version is not tight to an OS. It works on any OS as long as the application runs in a terminal emulator that understands ANSI escape codes (most of them do).

Related

Please Help me to understand old C code

I'm student and found this code on Internet. Can anyone explain algorythm used here?
#include<stdio.h>
#include<dos.h>
#include<conio.h>
#include<stdlib.h>
void main()
{
int count=50;
clrscr();
while(count--)
{
sound(10*random(100));
delay(75);
nosound();
textattr(random(16)+'a'+BLINK);
cprintf("*");
}
}
Looks like Turbo C code. sound will set the "PC beeper" playing given frequency, so the code will produce 50 random tones in the loop. It will also use textattr to select random color (most common text modes had 16 fixed colors, random(16) is for that reason) with blink attribute set and print an asterisk 50 times along with the sounds. This will require a real DOS text mode which actually supports blinking characters, in modern console window there will be no blinking.
Also, the include files and libraries are not standard C libraries, so basically code requires Turbo C to work without modification. The code is from simpler era of PC software, where applications had entire computer for themselves, and often used text mode.

OS X lock screen with pure C?

I know this is possible, because I have a binary I wrote a couple years ago to do exactly this. Unfortunately, I didn't save the source code.
I know that it was written in pure C, and I called against an OS X API and was able to lock the screen. Googling for "pure C OS X lock screen" and similar strings isn't getting me much; I saw documentation on how to do it in Objective C but that's not what I'm looking for.
Anyone have any idea how I accomplished this previously?
One way to do this is by using a call to system():
#include <stdlib.h>
int main(void) {
system("/System/Library/CoreServices/Menu\\ Extras/User.menu/Contents/Resources/CGSession -suspend");
return 0;
}
You're probably thinking of CGSCreateLoginSession() -- it's a private function and not documented by Apple. See this question for an example of its use.

Getting the coordinate of mouse click in C

I found this header file on google to perform mouse related events in C program but i am having no idea of int86 union REGS i,o; and what are other int86 type functions available in C? I am using windows OS and Turbo C.
#include<conio.h>
#include<stdio.h>
#include<dos.h>
initmouse();
void showmouseptr();
void restrictmousept(int,int,int,int);
void getmousepos(int *,int *,int *);
void hidemouseptr();
union REGS i,o;
initmouse()
{
i.x.ax=0;
int86(0x33,&i,&o);
return(o.x.ax);
}
void showmouseptr()
{
i.x.ax=1;
int86(0x33,&i,&o);
}
void restrictmouseptr(int x1,int y1,int x2,int y2)
{
i.x.ax=7;
i.x.cx=x1;
i.x.dx=x2;
int86(0x33,&i,&o);
i.x.ax=8;
i.x.cx=y1;
i.x.dx=y2;
int86(0x33,&i,&o);
}
void getmousepos(int *button,int *x,int *y)
{
i.x.ax=3;
int86(0x33,&i,&o);
*button=o.x.bx;
*x=o.x.cx;
*y=o.x.dx;
}
void hidemouseptr()
{
i.x.ax=2;
int86(0x33,&i,&o);
}
This looks like old code for MS-DOS to user the x86 interrupts to call system functions to get mouse coordinates. I would be surprised if this code still works in a command prompt of any modern computer. In fact, the header file at the top including dos.h would give this away.
in86() is how you "interrupt" the CPU in DOS mode. It is sort of the way functions are called in modern day operating systems. More info here: http://wiki.answers.com/Q/What_is_the_INT86_function_in_C_programming
A union is a method in C of defining data which can be accessed in different ways. More here: http://www.go4expert.com/forums/showthread.php?t=15.
It is unclear what you are trying to do, let alone what operating system you are running under. You probably want to pick a language first (C# might be a good start, assuming you are using Windows) and then look at the base class library for WinForms to learn how to respond to mouse events. There are fine tutorials on WinForms which will teach you how to respond to the mouse.
Discard that code: it is old 16-bit DOS which probably is not what you want.
It seems you're rather new to C. In that case, a better advice is to study well the language; check around the site for good learning references. "The C Programming Language", by Dennis Ritchie and Brian Kernighan is a good starting point.
Having said that, there are no int86 functions "in C". These are Borland Turbo C extensions. That was how one could manipulate the mouse in DOS, but nowadays it is different.
Note that the C language is, fundamentally, simply a programming language. It is intended to express algorithms. However, the C language standard also gives you a standard library: a set of predefined types, functions and macros you can use, to save time and portability. This library addresses some basic functionality, and mouse input handling is not one of them.
In other words, after you have studied C, you'll be ready to deal with specific operating system's APIs. This is needed, because the C standard library offers no way to manipulate any sort of input devices. You will also study some fundamentals regarding how input is handled in modern operating systems. For example, to handle mouse input you will most likely need to create a window (or widget) in order to receive mouse events -- implying that you will have to read a bit about the underlying windowing API.
There are some libraries which accesses the system's APIs for you and factor out the differences, offering you a programming alternative. It should be no different, though, from studying and using the system's API directly, except possibly for enhanced portability.
The int86 function calls the DOS Mouse Interrupt 33h. A dos interrupt is specific to the msdos operating system, so your code is only usable under msdos. 'union REGS' are the input and output registers that are used as parameters for the DOS interrupt. A DOS interrupt is similar to a system call in other operating systems.
You could use dosbox if you want to run turbo C programs under Windows/Linux etc
For example, on Windows, just make a desktop link that runs a batch script to run your program in dosbox, this is how the steam version of Doom works I think

GNU/Linux replacements for Turbo C functions `clrscr` and `cprintf`

I just moved to Linux for just a month. I've used Borland Turbo C for C programming but some of these functions do not work in GNU/Linux, so looking for help.
These are some of the functions I would like to replace:
- gotoxy
- cprintf
- clrscr
- initgraph/graphics.h
I would appreciate some code examples showing how to use any replacements.
In linux, you can use the ncurses library to use the terminal as a text buffer: move the cursor around, and write text. It can also draw windows and other hi-level widgets.
For gotoxy see move and wmove from ncurses (link).
For cprintf see printw.
You can clear the screen simply with clear().
In ncurses you also need to refresh the screen with refresh() after printw and clear().
Example program, which uses all the mentioned functions in ncurses:
#include <curses.h>
int main(int argc, char *argv[])
{
initscr();
clear();
move(15, 20);
printw("Test program: %s", argv[0]);
refresh();
getch();
endwin();
return 0;
}
Compile in gcc with: gcc program.c -lcurses
As for graphics, you have to choose a particular library.
If you need a similar experience as the low-level graphics.h, you are probably looking for directfb or svgalib.
If you want to render graphics in a window, SDL will be helpful.
The functions you refer to are part of Borland's proprietary library for console applications. You want to read about ncurses.
About graphics.h
Regarding using graphics.h in Linux is an easy task. I had the same problem a week ago. Well you can goggle with search term "graphics.h in Linux", and you will get many links and here is one.
http://www.rajivnair.in/2007/07/graphicsh-in-gnulinux.html.
About Clear Screen
For that, you have many options.
And the one is,
using system("clear") but it needs stdlib.h and it is slower in performance.
Here two links for you...
How do I clear the console in BOTH Windows and Linux using C++
cprogramming.com
About gotoxy
As mentioned in MichaƂ Trybus's Answer.
About cprintf
I Referred many links, but not getting the simple answers. Me too waiting for the answers for this.
But,In my experience whenever I want the output to be in some colored format , I will use graphics.h, though it is not required.That's why I doesn't had this question in my mind ever before.
You may find this link useful...
codeguru.com
About getch
I think you may already know about this. Instead of getch() in conio.h(not in ansi standard), you can use getchar() in stdio.h.
Just, I was answering the same questions in another thread:
void gotoxy(int x, int y) {
printf("%c[%d;%df",0x1B, y, x);
}
void clrscr(void) {
fprintf(stdout, "\033[2J\033[0;0f");
fflush(stdout);
}
void textcolor(int attr, int fg, int bg) {
printf("%c[%d;%d;%dm", 0x1B, attr, fg + 30, bg + 40);
}
Easy way to do it!

Adding a pass to gcc?

Has anybody added a pass to gcc ? or not really a pass but adding an option to do some nasty things... :-) ...
I still have the same problem about calling a function just before returning from another...so I would like to investigate it by implementing something in gcc...
Cheers.
EDIT: Adding a pass to a compiler means revisiting the tree to perform some optimizations or some analysis. I would like to emulate the behavior of __cyg_profile_func_exit but only for some functions and be able to access the original return value.
So I'm going to try to enhance my question. I would like to emulate really basic AOSD-like behavior. AOSD or Aspect oriented programming enables to add crosscutting concerns (debugging is a cross-cutting concern).
int main(int argc, char ** argv) {
return foo(argc);
}
int foo(int arg_num) {
int result = arg_num > 3 ? arg_num : 42;
return result;
}
int dbg(int returned) {
printf("Return %d", returned);
}
I would like to be able to say, I'd like to trigger the dbg function after function foo has been executed. The problem is how to tell the compiler to modify the control flow and execute dbg. dbg should be executed between return and foo(argc) ...
That's really like __cyg_profile_function_exit but only in some cases (and the problem in __cyg_profile_function_exit is that you cannot easily see and modify the returned value).
If you still are interested in adding a GCC pass, you can start reading up GCC Wiki material just about that:
http://gcc.gnu.org/wiki/WritingANewPass and "Implementing Passes" from http://www.airs.com/dnovillo/200711-GCC-Internals/ on how to, well, add a pass.
The intermediate representation you are interested in is called GIMPLE. Some introduction is at http://www.airs.com/dnovillo/200711-GCC-Internals/200711-GCC-Internals-3-IR.pdf
Other information at http://gcc.gnu.org/wiki/GettingStarted
Just for future reference: Upcoming versions of gcc (4.4.0+) will provide support for plugins specifically meant for use cases such as adding optimization passes to the compiler without having to bootstrap the whole compiler.
May 6, 2009:GCC can now be extended using a generic plugin framework on host platforms that support dynamically loadable objects.
(see gcc.gnu.org)
To answer your question: gcc is a pretty popular compiler platform to do compiler research on, so yes, I'm sure someone has done it.
However, I don't think this is something done in a weekend. Hooking into gcc's code-generation is not something you'd do over the weekend. (I'm not sure what your scope is and how much time you're willing to invest.) If you really do want to hack gcc to do what you want, you most certainly want to start by discussing it on one of the gcc mailing lists.
Tips: don't assume that people have read your other questions. If you want to refer to a question, please add a link to it if you want people to find it.
Do you need to use GCC? LLVM looks like it would work. It is written in C++, and it is very easy to write a pass.
It's an interesting question. I'm going to address concepts around the question rather than answer the question directly because, well, I don't know that much about gcc internals.
You've probably already explored some higher-level manipulation of the source code to achieve what you want to accomplish; some kind of
int main(int argc, char ** argv) {
return dbg(foo(argc));
}
inserted with with a macro on the function "foo", perhaps. If you're looking for a compiler hack, though, then you probably don't want to modify source.
There are some gcc extensions discussed here that sound a bit like what you're going for. If gcc has anything that does what you want, it'll probably be documented in the C-language extensions area of the documentation. I couldn't find anything that sounded exactly like what you've described, but perhaps since you understand best what you're looking for, you'll know better how to find it.
A gdb script would do a pretty good job of outputting debug, but it sounds like you've got bigger plans than simply doing printf's. Inserting significant logic into the code seems to be what you're after.
Which reminds me of some dynamic linker tricks I've come across recently. Library interposing could insert code around function calls without affecting the original source. The example I've encountered was on Solaris, but there is probably an analog on other platforms.
Just came across the -finstrument-functions option documented here
-finstrument-functions
Generate instrumentation calls for entry and exit to functions. Just after function
entry and just before function exit, the following profiling functions will be called
with the address of the current function and its call site. (On some platforms,
__builtin_return_address does not work beyond the current function, so the call site
information may not be available to the profiling functions otherwise.)
void __cyg_profile_func_enter (void *this_fn,
void *call_site);
void __cyg_profile_func_exit (void *this_fn,
void *call_site);
But I guess this doesn't work because you are not able to modify the return value from the profiling functions.
The GCC, the GNU Compiler Collection, is a large suite, and I don't think hacking up its source code is your answer for find problems in a single application.
It sounds like you are looking more-so for debugging or profiling tools, such as gdb, and its various front-ends (xgdb, ddd) and and gprof. Memory / Bounds checking tools like electric fence, glibc's memcheck, valgrind, and mudflap might help if this is a memory or pointer issues. Enabling compiler flags for warnings and newer C standards might be useful -std=c99 -Wall -pedantic.
I cannot understand what you mean by
I still have the same problem about
calling a function just before
returning from another.
So I am not certain what you are looking for. Can you give a trivial or pseudo-code example?
I.e.
#include <stdio.h>
void a(void) {
b();
}
void b(void) {
printf("Hello World\n");
}
int main(int ac, char *av[]) {
a();
return 0;
}

Resources