Having trouble understanding command line argument pointers
My professor cited this example in class. Its basically a version of the Unix more
command, and I'm unsure about a couple things in it
int main( int ac , char *av[] )
{
FILE *fp;
if ( ac == 1 )
do_more( stdin );
else
while ( --ac )
if ( (fp = fopen( *++av , "r" )) != NULL )
{
do_more(开发者_如何学运维 fp ) ;
fclose( fp );
}
else
exit(1);
return 0;
}
I understand that *fp
defines a file pointer, and that *av[] is the array of command line arguments. But what does *++av
mean in terms of operation?
read *++av like this:
++av // increment the pointer
*av // get the value at the pointer, which will be a char*
in this example, it will open every files passed on the command line.
also:
av[0] // program name
av[1] // parameter 1
av[2] // parameter 2
av[3] // parameter 3
av[ac - 1] // last parameter
Here is a better version of the code that should do the very same thing. Hopefully it will be easier to understand. The names argc
and argv
are de-facto standard, you should use them to make the code more understandable to other programmers.
int main (int argc, char *argv[])
{
FILE *fp;
int i;
if ( argc == 1 )
{
do_more( stdin );
}
else
{
for(i=1; i<argc; i++) /* skip the name of the executable, start at 1 */
{
fp = fopen (argv[i], "r");
if(fp == NULL)
{
/* error message, return etc here */
}
do_more( fp ) ;
fclose( fp );
}
}
return 0;
}
精彩评论