Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
325 views
in Technique[技术] by (71.8m points)

c - argv: Sanitizing wildcards

I was working on an example in the K&R C book where it asks you to essentially build an RPN calculator that takes input through command line arguments. My solution essentially iterates through the given arguments and spits out the answer, but I noticed something:

If I were to give the multiplication character (an asterisk) '*' without single quotes, gcc assumes that to be a wildcard input, so my input of

$./rpn 5 10 *

gives me an output of

read 5
read 10
read rpn
read rpn.c
= 0

Wrapping the asterisk with single quotes remedies the issue

$./rpn 5 10 '*'
read 5
read 10
read *
= 50

My question is would there be a way to sanitize input so that my program does not require the asterisk to be wrapped in single quotes, or is this behavior caused by something more fundamental (e.g. Linux/POSIX/UNIX binary execution and argument handling)?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

The shell is expanding the glob before executing the program. You quote the glob not because of GCC, but because of the shell. If you don't want this behavior then use a shell that does not honor globs.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...