Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C produce error if no argument is given in command line

In C, how can I produce an error if no arguments are given on the command line? I'm not using int main(int argc , * char[] argv). my main has no input so I'm getting my variable using scanf("%d", input)

like image 757
Nicky Mirfallah Avatar asked Feb 14 '16 18:02

Nicky Mirfallah


2 Answers

Your question is inconsistent: if you want to get arguments from the command line, you must define main with argc and argv.

Your prototype for main is incorrect, it should be:

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

If the program is run without any command line arguments, arc will have the value 1. You can test it this way:

int main(int argc, char *argv[]) {
    if (argc < 2) {
        printf("error: missing command line arguments\n");
        return 1;
    }
    ...
}

If you define main with int main(void) you have no portable access to command line arguments. Reading standard input has nothing to do with command line arguments.

like image 187
chqrlie Avatar answered Oct 09 '22 01:10

chqrlie


Given the code:

#include <stdio.h>

int main() {
  int input;
  int rc = scanf("%d", &input);
}

We can verify that scanf() was able to successfully get some input from the user by checking its return value. Only when rc == 1 has the user properly given us valid input.

If you'd like to know more, I recommend reading scanf's documentation.

like image 25
Bill Lynch Avatar answered Oct 09 '22 01:10

Bill Lynch