AGeek
AGeek

Reputation: 5225

Error when passing * as shell argument in C

I am working out a small program where I provide the command line arguments

For e.g. ./a.out 2 3 4 + *

When it comes ' * ', rather than printing the ' * ' itself, it prints the folders inside the directory' + ' works fine. Please let me know how to remove this error. I want to print ' * ' here.

#include <stdio.h>
int main(int argc, char *argv[])
{
   char *c;

   while(--argc > 0)
   {
      c = *++argv;
      if(strcmp(c,"+") == 0 )
      {
          printf("%s",c);
      }
      else if(strcmp(c,"-") == 0)
      {
          printf("%s",c);
      }
      else if(c[0] == '*')
      {
          printf("%s",c);
      }
   }
}

Upvotes: 3

Views: 171

Answers (2)

Silvio Donnini
Silvio Donnini

Reputation: 3303

Your shell interprets the '*' character as the list of all files in the current directory. The problem is not in your program but in the way you run it.

try:

./a.out 2 3 4 + \*

Upvotes: 4

Ignacio Vazquez-Abrams
Ignacio Vazquez-Abrams

Reputation: 798456

This has nothing to do with your code, but rather with your shell. If you want the shell to not glob wildcards then you will need to escape them, either with a backslash or with quotes.

./foo \*
./bar '*'

Upvotes: 9

Related Questions