I understand that argc
counts the number of arguments and argv
takes in the argument, but is their a way I can determine if my argument from argv
was inputted in a certain format like in parentheses and not in parenthesis. Such as ./a.out "Hello Word"
and ./a.out Hello World
?
Yes and no. Basically the only way to do this is to do a string comparison with a function like strcmp
. However, one thing that complicates the matter is that the shell you are using might remove the quotes before your program has a chance to see them. To make things worse, how this is handled depends on the shell, so what works for one shell might fail for another one. Posix shells (sh, bash, ksh and so forth) handles quotes the same way and do not offer any way of detecting it.
This program:
#include <stdio.h>
int main(int argc, char **argv)
{
printf("Number of arguments: %d\n", argc);
for(int i=0; i<argc; i++)
printf("Argument %d: %s\n", i, argv[i]);
}
yields this output for an asterisk as argument when using the shell bash:
/tmp/test$ ./a.out *
Number of arguments: 3
Argument 0: ./a.out
Argument 1: a.out
Argument 2: main.c
This is because the *
expands to all files in the current directory by the shell. Quotes usually group things that would otherwise be seen as two different arguments. If you want to pass quotes to bash you can escape them.
/tmp/test$ ./a.out "Hello world"
Number of arguments: 2
Argument 0: ./a.out
Argument 1: Hello world
/tmp/test$ ./a.out \"Hello world\"
Number of arguments: 3
Argument 0: ./a.out
Argument 1: "Hello
Argument 2: world"
So the answer is unfortunately no. There is no general method to do this. Some shells might provide tools to do this, but there is no guarantee for that, and even if they do, there is no standard way to do it.