1

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?

Squarepeg
  • 41
  • 4
  • 2
    Does this answer your question? [How do I properly compare strings in C?](https://stackoverflow.com/questions/8004237/how-do-i-properly-compare-strings-in-c) – lucidbrot Mar 26 '22 at 22:50
  • `argv[1] != "-size"` is _always_ true as those 2 pointers are always different. – chux - Reinstate Monica Mar 26 '22 at 22:50
  • 1
    The single quotes will be removed by your shell in any case; if you `printf("%s\n", argv[1])` it will not contain the single (or double) quotes. This isn't under your program's control. – David Maze Mar 27 '22 at 00:24

1 Answers1

2

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.

dbush
  • 205,898
  • 23
  • 218
  • 273
  • I see, would there be any way for me to compile the program in my makefile that would prevent the shell doing this? – Squarepeg Mar 27 '22 at 02:40
  • @Squarepeg What the shell does is completely independent of what any program it runs does. The arguments are read and interpreted by the shell before your program even runs. – dbush Mar 27 '22 at 02:43