tags:

views:

115

answers:

5

I have written a program in c. However once the program is finished it stops (duh). Is there a simple script that allows me to let the user start the program over again?

A: 

Sure, but how would you get the user to run that script? Wouldn't it be simpler to have the user simply re-run the program?

Andrew Hare
there isn't an easy way to let the user start the script over again?
HollerTrain
+3  A: 

Why not use loop (for, while) in the main itself: ( if the program is simple!)

main()
{

 while( Exit condition)
 {
  //logic
 }
}
aJ
+2  A: 
char cont_prog = 'n';
do {
    /* main program in here */
    printf("Do you want to start again? (y/n): ");
    cont_prog = getchar();
} while (cont_prog == 'y' || cont_prog == 'Y');

Essentially, you want to put you main prog in a loop, asking the user if they want to continue. You have to deal with the user entering in too much data (they type, 'yes', for example) and your buffer being full next time through the loop.

Nick Presta
+1 for the extra code effort. Also, Futurama rules.
Chris Lutz
\m/ for Fry! I realize that this snippet is rather rudimentary, but the user has been vague so I can't give much more than this.
Nick Presta
thanks for the code. however, it prompts me to start again and when i type 'y' it doesn't do anything :(
HollerTrain
You'll have to hit <Enter> after 'y'.
Fred Larson
+1  A: 

If you really want to re-launch the program without exiting (though I can't see why):

  1. Save argv (and I'll assume that argv[0] actually points to your executable, even though that is not guaranteed) if you want the same command line arguments.
  2. Consider saving the environment, if you might change it, and also want it to be repeated.
  3. man execv or execle. Just replace the currently running image with a new one that has the same command line

Frankly, looping would be easier, and can have the same semantics if you avoid global state, or arrange to be able to re-set it.

dmckee
A: 
#include <stdlib.h>
#ifdef WIN32
#define EXECUTABLE ".exe"
#else
#define EXECUTABLE
#endif
int main(void) {
    for (;;) system("executable_in_c" EXECUTABLE);
    return 0;
}

Compile this program, rename your old executable to "executable_in_c[.exe]"; rename this one to the name of your old executable ... voila!

pmg