开发者

* on the linux command line

I am making a little calculator in C, and i want to pass 开发者_开发百科simple arithmetic formulae to my program. But it really does not like me passing character '*' to my program. Why not? And how can I work around this without changing the asterix to something else? Thanks


The character * is the shell's trigger for expanding matching filenames.

There are several ways to deal with it:

  • Escape it when typing mycalc 5 \* 3
  • Place the whole expression in quotes and make sure the calculator's parser works that way: myprog "5 * 3"
  • Don't use the command line: use your own input instead.


* gets expanded to match all files in the current directory (this is called "globbing"). You need to quote or escape the *, or use a different symbol.


* will invoke globbing and expand to all files in the directory you're in. Just quote the * and run your program like

./yourprogram '10 * 10'

or

./yourprogram 10 '*' 10

With the first case, your program will get passed only 1 argument, argv[1] will be the string "10 * 10" , the second case you'll get passed 3 arguments


The Linux command shell (bash, tcsh, ksh, whatever) will expand the '*' into a list of files before your program even sees it. There's very little you can do about that - you could have the users put the asterisk in single quotes, or escape it with a backslash, or use 'x' instead. None is particularly user friendly.


One last technique not mentioned. Insteead of quoting/escaping every usage, you can turn off globbing. This way, if you want to use the calculator a lot, you don't have to escape every usage:

# For bash
set -o noglob

# For csh/tcsh
set noglob

# Now that noglob is set, you can safely use *
calc 3 * 3


* evaluates to "everything in the current directory" under bash. However, . works correctly and is often used as a symbol for multiplication in mathematics - specifically scalar multiplication.


The "calc" application that you can retrieve from deb repositories apt-get install calc can evaluate 3*3 but not 3 * 3


Try escaping it, the asterisk is a special character in C

Change * to \*

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜