How to stop a running program without crtl+c

Hi

I have a program with a loop and I would find a way to stop the loop when I press a key on keyboards (or a button)
I would that if a push the key (or button) the loop finish a the current step and then close so that it closes the opened file

with crtl+C it breaks and so it make some strange things with opened files.

I look into some guides I found on internet but I did not find any useful solution (I am new on this stuff and maybe I am not able to find the correct informations)

if you have some example o links it would be really helpful

I did something like that (sorry for the French name of some variables)

[code]//The 3 next functions allow the program to do something if a key is pressed

int mygetch(void) {//to get the code of the key that is pressed
struct termios oldt, newt;
int ch;
tcgetattr( STDIN_FILENO, &oldt);
newt = oldt;
newt.c_lflag &= ~( ICANON | ECHO );
tcsetattr( STDIN_FILENO, TCSANOW, &newt ) ;
ch = getchar();
tcsetattr( STDIN_FILENO, TCSANOW, &oldt ) ;
return ch;
}

int mykbhit(void) { //return 1 when a key is pressed
struct timeval tv = {0, 0};
fd_set readfds;

FD_ZERO(&readfds);
FD_SET(STDIN_FILENO, &readfds);

return select(STDIN_FILENO + 1, &readfds, NULL, NULL, &tv) == 1;
}

void mode_raw(int activer) { // to pas the terminal in raw mode. This allows to validate a command wihtout pressing Enter
static struct termios cooked;
static int raw_actif = 0;

if (raw_actif == activer)
return;

if (activer) {
struct termios raw;
tcgetattr(STDIN_FILENO, &cooked);
raw = cooked;
cfmakeraw(&raw);
tcsetattr(STDIN_FILENO, TCSANOW, &raw);
}
else
tcsetattr(STDIN_FILENO, TCSANOW, &cooked);

raw_actif = activer;
}

int main (int argc, char **argv) {
//do something

mode_raw(1); // switch on the raw mode
while(something) {
if(mykbhit())
if (mygetch()==27) { //27 corresponds to the Esc key
mode_raw(0);
break;
}
mode_raw(0); // switch off the raw mode
}[/code]

Thus, if you press the Escape key, the loop will be stopped.

I only tested this way on linux. I do not know for Mac OS or Windows.