0

Let's say I have a file test.c which accepts a text file and starts as follows:

int main(int argc, char **argv)
{
  ...
  return 0;
}

I will typically compile the file and execute the binary as follows: ./test input.txt.

Now, I wish to call the main function programmatically in another function in the same file. How should I proceed?

Kevin
  • 90
  • 6
  • Why do you want to call the `main` function? That's almost certainly the wrong way to achieve whatever it is you are trying to do. – kaylum Mar 28 '20 at 06:07
  • 1
    Don't do it ! Whatever you want to do should be a separate vunction called from main() and anywhere else you want to call it from... – John3136 Mar 28 '20 at 06:08
  • Is it an option for you to create a separate program (with its own `main()`) which calls this one? Or maybe just a script/batch? – Yunnosch Mar 28 '20 at 06:11
  • 1
    Note that you are not permitted to call [`main()` in C++](https://stackoverflow.com/a/18721336/15168) at all — but it is legitimate to call it in C, though it is unorthodox to do so except in programming contests such as the IOCCC (International Obfuscated C Code Contest). – Jonathan Leffler Mar 28 '20 at 07:04

1 Answers1

3

You can do this as follows:

#include <stdio.h>

int main(int argc, char *argv[]);

void func()
{
    char *argv[] = { "./test", "another.txt", NULL };
    main(2, argv);
}

int main(int argc, char *argv[])
{
    if (argc > 1) {
        printf("Processing %s...\n", argv[1]);
    }

    /* ... */

    func();

    return 0;
}

This should output something like:

Processing input.txt...
Processing another.txt...

Beware of endless recursion!

DaBler
  • 2,695
  • 2
  • 26
  • 46
  • I was especially looking on how to pass the second argument for which you provided a clear example. Thanks! – Kevin Mar 29 '20 at 13:48