Jump to content

Beginner: read argv

- - - - -

  • Please log in to reply
6 replies to this topic

#1
rfx

rfx

    Newbie

  • Members
  • Pip
  • 3 posts
Hi everybody,

I'm new to C and I'm fighting with pointers and argv's right now... I wrote:

#include <stdio.h>

#include <stdlib.h>


void main(int argc,char *argv[]){

	while(*argv){

		printf("%s",*argv);

		if(*argv == "show"){

			printf("Great");

		}

		*argv++;

	}

}

and the script should show "great" if it will be started with ./myscript show
What's wrong there?

#2
Ancient Dragon

Ancient Dragon

    Programming Expert

  • Members
  • PipPipPipPipPipPip
  • 400 posts
The array of pointers is NOT terminated with a NULL pointer. You have to test argc to find out how may strings are in argv. You also have to use strcmp() to compare two character arrays.

int main( int argc, char* argv[])

{

   int i;

  for(i = 0; i < argc; i++)

  {

      printf("%s\n", argv[i]);

      if( strcmp( argv[i], "SHOW") == 0)

        printf("Great\n");

}


Visit Grandpa's Forums, a social networking forum, with family-oriented arcade games, blogs, discussion forums, and photo albums.

#3
Zer033

Zer033

    Learning Programmer

  • Members
  • PipPipPip
  • 79 posts
Hi, I understand the code here, but what exactly is the TC trying to accomplish with ./myscript show?

#4
Ancient Dragon

Ancient Dragon

    Programming Expert

  • Members
  • PipPipPipPipPipPip
  • 400 posts
"./myscript show" is a common *nix console way to execute a program located in the current working directory. The "show" part is the parameter to the program "myscript".
Visit Grandpa's Forums, a social networking forum, with family-oriented arcade games, blogs, discussion forums, and photo albums.

#5
Warrior

Warrior

    Programmer

  • Members
  • PipPipPipPip
  • 130 posts

Quote

The array of pointers is NOT terminated with a NULL pointer.

The command line parameters are terminated by a NULL pointer as by the standard.

Warrior
Be a joke unto yourself!
Check out my blog at Flashcore

#6
rfx

rfx

    Newbie

  • Members
  • Pip
  • 3 posts
Thanks for all your help!! This works fine:

#include <stdio.h>
#include <stdlib.h>

void main(int argc,char *argv[]){
	while(*argv){
		printf("%s\n",*argv);
		if(strcmp(*argv,"show") == 0){
			printf("Great\n");
		}
		argv++;
	}
}


#7
manux

manux

    Programming Professional

  • Members
  • PipPipPipPipPip
  • 234 posts

Warrior said:

The command line parameters are terminated by a NULL pointer as by the standard.

Warrior
Still it's not clean and/or clear to write code that uses such premises, especially when argc is provided :)




1 user(s) are reading this topic

0 members, 1 guests, 0 anonymous users