1

Let's say I have a C program whose function declaration is void square(int n), (it's also defined) all it does it printf the squared value of n. I want to be able to run it from bash shell like so: square 5, where 5 is the input to the C program.

How would I go about this? I've looked into using getopt, read, I've read the man pages several times and watched a few getopt tutorials, but I can't seem to figure out a way to do this. I can't find an example of getopt that doesn't use flags in the examples, so I don't know how to apply it to a simple integer input. Could anyone share with me how to do this? I would really appreciate it.

thanos
  • 3,203
  • 4
  • 18
  • 27
  • 3
    don't need getopt for a simple single argument. all you need is argv/argc: http://crasseux.com/books/ctutorial/argc-and-argv.html – Marc B Mar 03 '14 at 19:23
  • @MarcB that link is extremely helpful! It cleared up a lot of things for me about argc and argv, I'm still a beginner at C, so I appreciate the concise information you linked there ^^ – thanos Mar 03 '14 at 22:24

1 Answers1

7

If you don't have any other command line options you need to handle, getopt is probably overkill. All you need is to read the value from argv:

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

    // need "2 args" because the program's name counts as 1
    if (argc != 2)
    {
        fprintf(stderr, "usage: square <n>\n");
        return -1;
    }

    // convert the first argument, argv[1], from string to int;
    // see note below about using strtol() instead
    n = atoi(argv[1]);

    square(n);

    return 0;
}

A better solution will use strtol() instead of atoi() in order to check if the conversion was valid.

Community
  • 1
  • 1
TypeIA
  • 16,916
  • 1
  • 38
  • 52
  • And you'd call it from the script like this `shell square 5`, right? – Fiddling Bits Mar 03 '14 at 19:26
  • 2
    @FiddlingBits If the program is compiled to an executable called `square` in the current directory, all you need to run (either from a prompt or a shell script) is `./square 5`. – TypeIA Mar 03 '14 at 19:28
  • @dvnrrs that block of code not only works, but your comments also helped explain it to me a tonne, thanks for the help! I'll definitely look into the man pages for `strtol()` and try to make an alternate solution with it for my own practice. – thanos Mar 03 '14 at 22:26