Reputation: 195
So I was reading The C Programming language and came across a section where programs were now allowed to have arguments... For example
find -x -n pattern
Here, -x
means except.
-n
means numbered lines...
and pattern
is what it will look for, in another few lines of input.
Now they regard find
as *argv[0]
, -x
and -n
at *++argv[0]
, and pattern
as *++argv[0]
. How does a computer know one arg from the other?
If 3 things are all equal to *++argv[0]
, then they stay at argv[1]
, but all of them??
Could anyone please explain in depth?
Upvotes: 2
Views: 180
Reputation: 45045
argv[0] = program name = "find"
argv[1] = first argument = "-x"
argv[2] = second argument = "-n"
argv[3] = third argument = "pattern"
argc
= 4, so you know there are no other arguments to process.
Don't be confused by the use of the pre-increment operator in expressions like *++argv[0]
. The arguments are passed in separate array elements.
When the shell executes your command, it uses whitespace to divide the command line up into the program name and arguments and pass them to your program. Sometimes you need to work around that by using double quotes, for example, if you need to deal with a file whose name contains embedded spaces:
mv some stupid filename sane_filename
This won't work because "some" "stupid" "filename" will be seen as separate arguments. But you can do this:
mv "some stupid filename" sane_filename
to get a single argument with embedded spaces.
Upvotes: 3
Reputation: 798636
The ++n
preincrement operator changes the variable it is applied to. The first time ++argv
is executed, indexing it at 0
actually points to element 1
of the original value argv
had, the second time it points to element 2
, and so on.
Upvotes: 2