Issue
I have a c file such that I pass arguments to as such:
./cfile [-size number]
e.g.
./cfile -size 22
Here is an example code for such a file:
int main(int argc, char** argv) {
if (argv[1] != "-size") {
fprintf(stderr, "Wrong format");
return 1;
}
// get_number is some function that returns int value of number if number, NULL otherwise
if (get_number(argv[2]) == NULL) {
fprintf(stderr, "Wrong format");
return 1;
}
return 0;
}
However, when I write
./cfile '-size' '22'
I cannot find a way of making C determine that the apostrophes should not be there.
I want to throw an error due to the apostrophes on each argument, but c seems to treat them as if they are not there.
Is there any way of doing this?
Solution
The quotes are interpreted by the shell in order to separate the arguments. They are removed before your program even sees them.
So your program will only see -size
for argv[1]
, not '-size'
.
Also, when comparing strings, you need to use strcmp
. Using !=
or ==
to compare strings is actually comparing pointer values which is not what you want.
Answered By – dbush
Answer Checked By – Mary Flores (BugsFixing Volunteer)