-1

How does one go about making it a requirement for parameters to be passed while executing a program through a Linux terminal?

This is in C, specifically.

To explain better.. In terminal, I need to be able to run the program like so

./program FILENAME secondParameter

Also need to return the error message for this if the parameters are not given and then discontinue the program from running.

I can give more info if needed, seems like a pretty straight forward question.

m96
  • 199
  • 1
  • 3
  • 10
  • 1
    learn about `main()` syntax `main(int argc, char* argv[])` – Grijesh Chauhan Sep 05 '13 at 05:12
  • 1
    @GrijeshChauhan: You mean `int main(int argc, char *argv[])`. Or, exactly equivalently but clearer: `int main(int argc, char **argv)` – Keith Thompson Sep 05 '13 at 05:14
  • 1
    Look up `argc` and `argv` in the index of your C textbook. – Keith Thompson Sep 05 '13 at 05:15
  • @KeithThompson Yes! , @ Zorca: read 1: [Arguments to main in C](http://stackoverflow.com/questions/4176326/arguments-to-main-in-c) 2: [10.2. Arguments to main](http://publications.gbdirect.co.uk/c_book/chapter10/arguments_to_main.html) 3: [Wiki: `main()`](http://en.wikipedia.org/wiki/Main_function#C_and_C.2B.2B) – Grijesh Chauhan Sep 05 '13 at 05:18

1 Answers1

4

Simple check on argc can do what you are looking for:

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

  if(argc != 3)
  {
    printf("Usage error. Program expects two arguments. \n");
    printf("Usage: ./program FILENAME secondParameter \n");
    exit(1);
  }
/* Rest of your code */

}

You need to learn about arguments passing to main() in C. argv[0] is the program name and hence the condition is argc != 3 i.e. If you give less than or more than 2 arguments, you'll get usage error.

P.P
  • 117,907
  • 20
  • 175
  • 238
  • Ah okay. It's been a few months since I've written any code so I'm a bit rusty. Is it possible to use perror() to return an error message generated without me typing out an actual error message? I was told to use perror and errno for errors. – m96 Sep 05 '13 at 05:27
  • 1
    perror retrieves the details about failure from `errno` from `` about the system call/library call failures. Yours is not such a failure but a user-defined error which won't set any `errno` unless you set it yourself (which I don't recommend for what you do). `perror` can't magically expect know about a user-defined usage error. So I wouldn't suggest using perror. – P.P Sep 05 '13 at 05:44