Zach Smith
Zach Smith

Reputation: 5674

allow user to start program again in c?

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?

Upvotes: 0

Views: 8517

Answers (5)

pmg
pmg

Reputation: 108968

#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!

Upvotes: 0

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.

Upvotes: 1

Nick Presta
Nick Presta

Reputation: 28665

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.

Upvotes: 2

aJ.
aJ.

Reputation: 35450

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

main()
{

 while( Exit condition)
 {
  //logic
 }
}

Upvotes: 3

Andrew Hare
Andrew Hare

Reputation: 351466

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?

Upvotes: 0

Related Questions