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.

2
  • 3
    don't need getopt for a simple single argument. all you need is argv/argc: crasseux.com/books/ctutorial/argc-and-argv.html Commented Mar 3, 2014 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 ^^ Commented Mar 3, 2014 at 22:24

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

3 Comments

And you'd call it from the script like this shell square 5, right?
@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.
@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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.