Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using argv in C?

Tags:

c

argv

For an assignment, I am required to have command line arguments for my C program. I've used argc/argv before (in C++) without trouble, but I'm unsure if C style strings are affecting how this works. Here is the start of my main:

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

  if(argc>1){
    printf("0 is %s, 1 is %s\n",argv[0],argv[1]);
    if(argv[1]=="-e"){
        // Do some stuff with argv[2]
        system("PAUSE");
    }
    else{
        printf("Error: Incorrect usage - first argument must be -e");
        return 0;
    }
  }

So I am calling my program as "program.exe -e myargstuff" but I am getting the "Error: Incorrect Usage..." output, even though my printf() tells me that argv[1] is "-e". Some help, please? Thanks!

like image 315
Joe Avatar asked Feb 20 '10 02:02

Joe


3 Answers

Change:

if(argv[1]=="-e"){

to

if(strcmp(argv[1], "-e") == 0){

and include string.h.

like image 133
Dawid Avatar answered Nov 10 '22 12:11

Dawid


The line

if(argv[1]=="-e"){

compares pointers, not strings. Use the strcmp function instead:

if(strcmp(argv[1],"-e")==0){
like image 28
jgottula Avatar answered Nov 10 '22 11:11

jgottula


Check out getopt() and related functions; it'll make your life a lot easier.

like image 5
Carl Norum Avatar answered Nov 10 '22 11:11

Carl Norum