Question

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.

Was it helpful?

Solution

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top